es6.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141
  1. 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};
  2. 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)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * 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)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * 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)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * 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)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * 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)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * 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)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * 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.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * 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".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. 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);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * 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"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. 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);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * 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)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * 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
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. 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]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. 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]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. 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);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. 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);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. 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);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. 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);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. 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);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. 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);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * 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"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * 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".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. 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);
  6093. };
  6094. /**
  6095. * 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"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * 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".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. 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);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. 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);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. 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);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. 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);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. 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);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. 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);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. 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);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. 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);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * 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.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. 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)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. 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;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. 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)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * 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.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * 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).
  8129. * 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.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @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.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._deferUnregister(observer);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._deferUnregister(this._observers[index]);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this._remove(observer);
  8218. });
  8219. };
  8220. // This should only be called when not iterating over _observers to avoid callback skipping.
  8221. // Removes an observer from the _observer Array.
  8222. Observable.prototype._remove = function (observer) {
  8223. if (!observer) {
  8224. return false;
  8225. }
  8226. var index = this._observers.indexOf(observer);
  8227. if (index !== -1) {
  8228. this._observers.splice(index, 1);
  8229. return true;
  8230. }
  8231. return false;
  8232. };
  8233. /**
  8234. * Notify all Observers by calling their respective callback with the given data
  8235. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8236. * @param eventData defines the data to send to all observers
  8237. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8238. * @param target defines the original target of the state
  8239. * @param currentTarget defines the current target of the state
  8240. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8241. */
  8242. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8243. if (mask === void 0) { mask = -1; }
  8244. if (!this._observers.length) {
  8245. return true;
  8246. }
  8247. var state = this._eventState;
  8248. state.mask = mask;
  8249. state.target = target;
  8250. state.currentTarget = currentTarget;
  8251. state.skipNextObservers = false;
  8252. state.lastReturnValue = eventData;
  8253. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8254. var obs = _a[_i];
  8255. if (obs._willBeUnregistered) {
  8256. continue;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8261. }
  8262. else {
  8263. state.lastReturnValue = obs.callback(eventData, state);
  8264. }
  8265. if (obs.unregisterOnNextCall) {
  8266. this._deferUnregister(obs);
  8267. }
  8268. }
  8269. if (state.skipNextObservers) {
  8270. return false;
  8271. }
  8272. }
  8273. return true;
  8274. };
  8275. /**
  8276. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8277. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8278. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8279. * and it is crucial that all callbacks will be executed.
  8280. * The order of the callbacks is kept, callbacks are not executed parallel.
  8281. *
  8282. * @param eventData The data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. * @param target defines the callback target (see EventState)
  8285. * @param currentTarget defines he current object in the bubbling phase
  8286. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8287. */
  8288. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8289. var _this = this;
  8290. if (mask === void 0) { mask = -1; }
  8291. // create an empty promise
  8292. var p = Promise.resolve(eventData);
  8293. // no observers? return this promise.
  8294. if (!this._observers.length) {
  8295. return p;
  8296. }
  8297. var state = this._eventState;
  8298. state.mask = mask;
  8299. state.target = target;
  8300. state.currentTarget = currentTarget;
  8301. state.skipNextObservers = false;
  8302. // execute one callback after another (not using Promise.all, the order is important)
  8303. this._observers.forEach(function (obs) {
  8304. if (state.skipNextObservers) {
  8305. return;
  8306. }
  8307. if (obs._willBeUnregistered) {
  8308. return;
  8309. }
  8310. if (obs.mask & mask) {
  8311. if (obs.scope) {
  8312. p = p.then(function (lastReturnedValue) {
  8313. state.lastReturnValue = lastReturnedValue;
  8314. return obs.callback.apply(obs.scope, [eventData, state]);
  8315. });
  8316. }
  8317. else {
  8318. p = p.then(function (lastReturnedValue) {
  8319. state.lastReturnValue = lastReturnedValue;
  8320. return obs.callback(eventData, state);
  8321. });
  8322. }
  8323. if (obs.unregisterOnNextCall) {
  8324. _this._deferUnregister(obs);
  8325. }
  8326. }
  8327. });
  8328. // return the eventData
  8329. return p.then(function () { return eventData; });
  8330. };
  8331. /**
  8332. * Notify a specific observer
  8333. * @param observer defines the observer to notify
  8334. * @param eventData defines the data to be sent to each callback
  8335. * @param mask is used to filter observers defaults to -1
  8336. */
  8337. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8338. if (mask === void 0) { mask = -1; }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.skipNextObservers = false;
  8342. observer.callback(eventData, state);
  8343. };
  8344. /**
  8345. * Gets a boolean indicating if the observable has at least one observer
  8346. * @returns true is the Observable has at least one Observer registered
  8347. */
  8348. Observable.prototype.hasObservers = function () {
  8349. return this._observers.length > 0;
  8350. };
  8351. /**
  8352. * Clear the list of observers
  8353. */
  8354. Observable.prototype.clear = function () {
  8355. this._observers = new Array();
  8356. this._onObserverAdded = null;
  8357. };
  8358. /**
  8359. * Clone the current observable
  8360. * @returns a new observable
  8361. */
  8362. Observable.prototype.clone = function () {
  8363. var result = new Observable();
  8364. result._observers = this._observers.slice(0);
  8365. return result;
  8366. };
  8367. /**
  8368. * Does this observable handles observer registered with a given mask
  8369. * @param mask defines the mask to be tested
  8370. * @return whether or not one observer registered with the given mask is handeled
  8371. **/
  8372. Observable.prototype.hasSpecificMask = function (mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8375. var obs = _a[_i];
  8376. if (obs.mask & mask || obs.mask === mask) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. };
  8382. return Observable;
  8383. }());
  8384. BABYLON.Observable = Observable;
  8385. })(BABYLON || (BABYLON = {}));
  8386. //# sourceMappingURL=babylon.observable.js.map
  8387. var BABYLON;
  8388. (function (BABYLON) {
  8389. var SmartArray = /** @class */ (function () {
  8390. function SmartArray(capacity) {
  8391. this.length = 0;
  8392. this.data = new Array(capacity);
  8393. this._id = SmartArray._GlobalId++;
  8394. }
  8395. SmartArray.prototype.push = function (value) {
  8396. this.data[this.length++] = value;
  8397. if (this.length > this.data.length) {
  8398. this.data.length *= 2;
  8399. }
  8400. };
  8401. SmartArray.prototype.forEach = function (func) {
  8402. for (var index = 0; index < this.length; index++) {
  8403. func(this.data[index]);
  8404. }
  8405. };
  8406. SmartArray.prototype.sort = function (compareFn) {
  8407. this.data.sort(compareFn);
  8408. };
  8409. SmartArray.prototype.reset = function () {
  8410. this.length = 0;
  8411. };
  8412. SmartArray.prototype.dispose = function () {
  8413. this.reset();
  8414. if (this.data) {
  8415. this.data.length = 0;
  8416. this.data = [];
  8417. }
  8418. };
  8419. SmartArray.prototype.concat = function (array) {
  8420. if (array.length === 0) {
  8421. return;
  8422. }
  8423. if (this.length + array.length > this.data.length) {
  8424. this.data.length = (this.length + array.length) * 2;
  8425. }
  8426. for (var index = 0; index < array.length; index++) {
  8427. this.data[this.length++] = (array.data || array)[index];
  8428. }
  8429. };
  8430. SmartArray.prototype.indexOf = function (value) {
  8431. var position = this.data.indexOf(value);
  8432. if (position >= this.length) {
  8433. return -1;
  8434. }
  8435. return position;
  8436. };
  8437. SmartArray.prototype.contains = function (value) {
  8438. return this.data.indexOf(value) !== -1;
  8439. };
  8440. // Statics
  8441. SmartArray._GlobalId = 0;
  8442. return SmartArray;
  8443. }());
  8444. BABYLON.SmartArray = SmartArray;
  8445. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8446. __extends(SmartArrayNoDuplicate, _super);
  8447. function SmartArrayNoDuplicate() {
  8448. var _this = _super !== null && _super.apply(this, arguments) || this;
  8449. _this._duplicateId = 0;
  8450. return _this;
  8451. }
  8452. SmartArrayNoDuplicate.prototype.push = function (value) {
  8453. _super.prototype.push.call(this, value);
  8454. if (!value.__smartArrayFlags) {
  8455. value.__smartArrayFlags = {};
  8456. }
  8457. value.__smartArrayFlags[this._id] = this._duplicateId;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8461. return false;
  8462. }
  8463. this.push(value);
  8464. return true;
  8465. };
  8466. SmartArrayNoDuplicate.prototype.reset = function () {
  8467. _super.prototype.reset.call(this);
  8468. this._duplicateId++;
  8469. };
  8470. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8471. if (array.length === 0) {
  8472. return;
  8473. }
  8474. if (this.length + array.length > this.data.length) {
  8475. this.data.length = (this.length + array.length) * 2;
  8476. }
  8477. for (var index = 0; index < array.length; index++) {
  8478. var item = (array.data || array)[index];
  8479. this.pushNoDuplicate(item);
  8480. }
  8481. };
  8482. return SmartArrayNoDuplicate;
  8483. }(SmartArray));
  8484. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.smartArray.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. /** Class used to store color gradient */
  8490. var ColorGradient = /** @class */ (function () {
  8491. function ColorGradient() {
  8492. }
  8493. /**
  8494. * Will get a color picked randomly between color1 and color2.
  8495. * If color2 is undefined then color1 will be used
  8496. * @param result defines the target Color4 to store the result in
  8497. */
  8498. ColorGradient.prototype.getColorToRef = function (result) {
  8499. if (!this.color2) {
  8500. result.copyFrom(this.color1);
  8501. return;
  8502. }
  8503. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8504. };
  8505. return ColorGradient;
  8506. }());
  8507. BABYLON.ColorGradient = ColorGradient;
  8508. /** Class used to store factor gradient */
  8509. var FactorGradient = /** @class */ (function () {
  8510. function FactorGradient() {
  8511. }
  8512. /**
  8513. * Will get a number picked randomly between factor1 and factor2.
  8514. * If factor2 is undefined then factor1 will be used
  8515. * @returns the picked number
  8516. */
  8517. FactorGradient.prototype.getFactor = function () {
  8518. if (this.factor2 === undefined) {
  8519. return this.factor1;
  8520. }
  8521. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8522. };
  8523. return FactorGradient;
  8524. }());
  8525. BABYLON.FactorGradient = FactorGradient;
  8526. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8527. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8528. var LoadFileError = /** @class */ (function (_super) {
  8529. __extends(LoadFileError, _super);
  8530. function LoadFileError(message, request) {
  8531. var _this = _super.call(this, message) || this;
  8532. _this.request = request;
  8533. _this.name = "LoadFileError";
  8534. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8535. return _this;
  8536. }
  8537. // Polyfill for Object.setPrototypeOf if necessary.
  8538. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8539. return LoadFileError;
  8540. }(Error));
  8541. BABYLON.LoadFileError = LoadFileError;
  8542. var RetryStrategy = /** @class */ (function () {
  8543. function RetryStrategy() {
  8544. }
  8545. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8546. if (maxRetries === void 0) { maxRetries = 3; }
  8547. if (baseInterval === void 0) { baseInterval = 500; }
  8548. return function (url, request, retryIndex) {
  8549. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8550. return -1;
  8551. }
  8552. return Math.pow(2, retryIndex) * baseInterval;
  8553. };
  8554. };
  8555. return RetryStrategy;
  8556. }());
  8557. BABYLON.RetryStrategy = RetryStrategy;
  8558. // Screenshots
  8559. var screenshotCanvas;
  8560. var cloneValue = function (source, destinationObject) {
  8561. if (!source)
  8562. return null;
  8563. if (source instanceof BABYLON.Mesh) {
  8564. return null;
  8565. }
  8566. if (source instanceof BABYLON.SubMesh) {
  8567. return source.clone(destinationObject);
  8568. }
  8569. else if (source.clone) {
  8570. return source.clone();
  8571. }
  8572. return null;
  8573. };
  8574. var Tools = /** @class */ (function () {
  8575. function Tools() {
  8576. }
  8577. /**
  8578. * Interpolates between a and b via alpha
  8579. * @param a The lower value (returned when alpha = 0)
  8580. * @param b The upper value (returned when alpha = 1)
  8581. * @param alpha The interpolation-factor
  8582. * @return The mixed value
  8583. */
  8584. Tools.Mix = function (a, b, alpha) {
  8585. return a * (1 - alpha) + b * alpha;
  8586. };
  8587. Tools.Instantiate = function (className) {
  8588. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8589. return Tools.RegisteredExternalClasses[className];
  8590. }
  8591. var arr = className.split(".");
  8592. var fn = (window || this);
  8593. for (var i = 0, len = arr.length; i < len; i++) {
  8594. fn = fn[arr[i]];
  8595. }
  8596. if (typeof fn !== "function") {
  8597. return null;
  8598. }
  8599. return fn;
  8600. };
  8601. /**
  8602. * Provides a slice function that will work even on IE
  8603. * @param data defines the array to slice
  8604. * @param start defines the start of the data (optional)
  8605. * @param end defines the end of the data (optional)
  8606. * @returns the new sliced array
  8607. */
  8608. Tools.Slice = function (data, start, end) {
  8609. if (data.slice) {
  8610. return data.slice(start, end);
  8611. }
  8612. return Array.prototype.slice.call(data, start, end);
  8613. };
  8614. Tools.SetImmediate = function (action) {
  8615. if (window.setImmediate) {
  8616. window.setImmediate(action);
  8617. }
  8618. else {
  8619. setTimeout(action, 1);
  8620. }
  8621. };
  8622. Tools.IsExponentOfTwo = function (value) {
  8623. var count = 1;
  8624. do {
  8625. count *= 2;
  8626. } while (count < value);
  8627. return count === value;
  8628. };
  8629. /**
  8630. * Returns the nearest 32-bit single precision float representation of a Number
  8631. * @param value A Number. If the parameter is of a different type, it will get converted
  8632. * to a number or to NaN if it cannot be converted
  8633. * @returns number
  8634. */
  8635. Tools.FloatRound = function (value) {
  8636. if (Math.fround) {
  8637. return Math.fround(value);
  8638. }
  8639. return (Tools._tmpFloatArray[0] = value);
  8640. };
  8641. /**
  8642. * Find the next highest power of two.
  8643. * @param x Number to start search from.
  8644. * @return Next highest power of two.
  8645. */
  8646. Tools.CeilingPOT = function (x) {
  8647. x--;
  8648. x |= x >> 1;
  8649. x |= x >> 2;
  8650. x |= x >> 4;
  8651. x |= x >> 8;
  8652. x |= x >> 16;
  8653. x++;
  8654. return x;
  8655. };
  8656. /**
  8657. * Find the next lowest power of two.
  8658. * @param x Number to start search from.
  8659. * @return Next lowest power of two.
  8660. */
  8661. Tools.FloorPOT = function (x) {
  8662. x = x | (x >> 1);
  8663. x = x | (x >> 2);
  8664. x = x | (x >> 4);
  8665. x = x | (x >> 8);
  8666. x = x | (x >> 16);
  8667. return x - (x >> 1);
  8668. };
  8669. /**
  8670. * Find the nearest power of two.
  8671. * @param x Number to start search from.
  8672. * @return Next nearest power of two.
  8673. */
  8674. Tools.NearestPOT = function (x) {
  8675. var c = Tools.CeilingPOT(x);
  8676. var f = Tools.FloorPOT(x);
  8677. return (c - x) > (x - f) ? f : c;
  8678. };
  8679. Tools.GetExponentOfTwo = function (value, max, mode) {
  8680. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8681. var pot;
  8682. switch (mode) {
  8683. case BABYLON.Engine.SCALEMODE_FLOOR:
  8684. pot = Tools.FloorPOT(value);
  8685. break;
  8686. case BABYLON.Engine.SCALEMODE_NEAREST:
  8687. pot = Tools.NearestPOT(value);
  8688. break;
  8689. case BABYLON.Engine.SCALEMODE_CEILING:
  8690. default:
  8691. pot = Tools.CeilingPOT(value);
  8692. break;
  8693. }
  8694. return Math.min(pot, max);
  8695. };
  8696. Tools.GetFilename = function (path) {
  8697. var index = path.lastIndexOf("/");
  8698. if (index < 0)
  8699. return path;
  8700. return path.substring(index + 1);
  8701. };
  8702. /**
  8703. * Extracts the "folder" part of a path (everything before the filename).
  8704. * @param uri The URI to extract the info from
  8705. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8706. * @returns The "folder" part of the path
  8707. */
  8708. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8709. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8710. var index = uri.lastIndexOf("/");
  8711. if (index < 0) {
  8712. if (returnUnchangedIfNoSlash) {
  8713. return uri;
  8714. }
  8715. return "";
  8716. }
  8717. return uri.substring(0, index + 1);
  8718. };
  8719. Tools.GetDOMTextContent = function (element) {
  8720. var result = "";
  8721. var child = element.firstChild;
  8722. while (child) {
  8723. if (child.nodeType === 3) {
  8724. result += child.textContent;
  8725. }
  8726. child = child.nextSibling;
  8727. }
  8728. return result;
  8729. };
  8730. Tools.ToDegrees = function (angle) {
  8731. return angle * 180 / Math.PI;
  8732. };
  8733. Tools.ToRadians = function (angle) {
  8734. return angle * Math.PI / 180;
  8735. };
  8736. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8737. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8738. var output = "";
  8739. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8740. var i = 0;
  8741. var bytes = new Uint8Array(buffer);
  8742. while (i < bytes.length) {
  8743. chr1 = bytes[i++];
  8744. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8745. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8746. enc1 = chr1 >> 2;
  8747. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8748. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8749. enc4 = chr3 & 63;
  8750. if (isNaN(chr2)) {
  8751. enc3 = enc4 = 64;
  8752. }
  8753. else if (isNaN(chr3)) {
  8754. enc4 = 64;
  8755. }
  8756. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8757. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8758. }
  8759. return "data:image/png;base64," + output;
  8760. };
  8761. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8762. if (bias === void 0) { bias = null; }
  8763. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8764. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8765. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8766. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8767. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8768. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8769. }
  8770. if (bias) {
  8771. minimum.x -= minimum.x * bias.x + bias.y;
  8772. minimum.y -= minimum.y * bias.x + bias.y;
  8773. minimum.z -= minimum.z * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. maximum.z += maximum.z * bias.x + bias.y;
  8777. }
  8778. return {
  8779. minimum: minimum,
  8780. maximum: maximum
  8781. };
  8782. };
  8783. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8784. if (bias === void 0) { bias = null; }
  8785. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8786. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8787. if (!stride) {
  8788. stride = 3;
  8789. }
  8790. for (var index = start; index < start + count; index++) {
  8791. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8792. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8793. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8794. }
  8795. if (bias) {
  8796. minimum.x -= minimum.x * bias.x + bias.y;
  8797. minimum.y -= minimum.y * bias.x + bias.y;
  8798. minimum.z -= minimum.z * bias.x + bias.y;
  8799. maximum.x += maximum.x * bias.x + bias.y;
  8800. maximum.y += maximum.y * bias.x + bias.y;
  8801. maximum.z += maximum.z * bias.x + bias.y;
  8802. }
  8803. return {
  8804. minimum: minimum,
  8805. maximum: maximum
  8806. };
  8807. };
  8808. Tools.Vector2ArrayFeeder = function (array) {
  8809. return function (index) {
  8810. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8811. var length = isFloatArray ? array.length / 2 : array.length;
  8812. if (index >= length) {
  8813. return null;
  8814. }
  8815. if (isFloatArray) {
  8816. var fa = array;
  8817. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8818. }
  8819. var a = array;
  8820. return a[index];
  8821. };
  8822. };
  8823. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8824. if (bias === void 0) { bias = null; }
  8825. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8826. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8827. var i = 0;
  8828. var cur = feeder(i++);
  8829. while (cur) {
  8830. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8831. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8832. cur = feeder(i++);
  8833. }
  8834. if (bias) {
  8835. minimum.x -= minimum.x * bias.x + bias.y;
  8836. minimum.y -= minimum.y * bias.x + bias.y;
  8837. maximum.x += maximum.x * bias.x + bias.y;
  8838. maximum.y += maximum.y * bias.x + bias.y;
  8839. }
  8840. return {
  8841. minimum: minimum,
  8842. maximum: maximum
  8843. };
  8844. };
  8845. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8846. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8847. return null;
  8848. return Array.isArray(obj) ? obj : [obj];
  8849. };
  8850. // Misc.
  8851. Tools.GetPointerPrefix = function () {
  8852. var eventPrefix = "pointer";
  8853. // Check if pointer events are supported
  8854. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8855. eventPrefix = "mouse";
  8856. }
  8857. return eventPrefix;
  8858. };
  8859. /**
  8860. * @param func - the function to be called
  8861. * @param requester - the object that will request the next frame. Falls back to window.
  8862. */
  8863. Tools.QueueNewFrame = function (func, requester) {
  8864. if (!Tools.IsWindowObjectExist()) {
  8865. return setTimeout(func, 16);
  8866. }
  8867. if (!requester) {
  8868. requester = window;
  8869. }
  8870. if (requester.requestAnimationFrame) {
  8871. return requester.requestAnimationFrame(func);
  8872. }
  8873. else if (requester.msRequestAnimationFrame) {
  8874. return requester.msRequestAnimationFrame(func);
  8875. }
  8876. else if (requester.webkitRequestAnimationFrame) {
  8877. return requester.webkitRequestAnimationFrame(func);
  8878. }
  8879. else if (requester.mozRequestAnimationFrame) {
  8880. return requester.mozRequestAnimationFrame(func);
  8881. }
  8882. else if (requester.oRequestAnimationFrame) {
  8883. return requester.oRequestAnimationFrame(func);
  8884. }
  8885. else {
  8886. return window.setTimeout(func, 16);
  8887. }
  8888. };
  8889. Tools.RequestFullscreen = function (element) {
  8890. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8891. if (!requestFunction)
  8892. return;
  8893. requestFunction.call(element);
  8894. };
  8895. Tools.ExitFullscreen = function () {
  8896. if (document.exitFullscreen) {
  8897. document.exitFullscreen();
  8898. }
  8899. else if (document.mozCancelFullScreen) {
  8900. document.mozCancelFullScreen();
  8901. }
  8902. else if (document.webkitCancelFullScreen) {
  8903. document.webkitCancelFullScreen();
  8904. }
  8905. else if (document.msCancelFullScreen) {
  8906. document.msCancelFullScreen();
  8907. }
  8908. };
  8909. Tools.SetCorsBehavior = function (url, element) {
  8910. if (url && url.indexOf("data:") === 0) {
  8911. return;
  8912. }
  8913. if (Tools.CorsBehavior) {
  8914. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8915. element.crossOrigin = Tools.CorsBehavior;
  8916. }
  8917. else {
  8918. var result = Tools.CorsBehavior(url);
  8919. if (result) {
  8920. element.crossOrigin = result;
  8921. }
  8922. }
  8923. }
  8924. };
  8925. // External files
  8926. Tools.CleanUrl = function (url) {
  8927. url = url.replace(/#/mg, "%23");
  8928. return url;
  8929. };
  8930. /**
  8931. * Loads an image as an HTMLImageElement.
  8932. * @param input url string, ArrayBuffer, or Blob to load
  8933. * @param onLoad callback called when the image successfully loads
  8934. * @param onError callback called when the image fails to load
  8935. * @param database database for caching
  8936. * @returns the HTMLImageElement of the loaded image
  8937. */
  8938. Tools.LoadImage = function (input, onLoad, onError, database) {
  8939. var url;
  8940. var usingObjectURL = false;
  8941. if (input instanceof ArrayBuffer) {
  8942. url = URL.createObjectURL(new Blob([input]));
  8943. usingObjectURL = true;
  8944. }
  8945. else if (input instanceof Blob) {
  8946. url = URL.createObjectURL(input);
  8947. usingObjectURL = true;
  8948. }
  8949. else {
  8950. url = Tools.CleanUrl(input);
  8951. url = Tools.PreprocessUrl(input);
  8952. }
  8953. var img = new Image();
  8954. Tools.SetCorsBehavior(url, img);
  8955. var loadHandler = function () {
  8956. if (usingObjectURL && img.src) {
  8957. URL.revokeObjectURL(img.src);
  8958. }
  8959. img.removeEventListener("load", loadHandler);
  8960. img.removeEventListener("error", errorHandler);
  8961. onLoad(img);
  8962. };
  8963. var errorHandler = function (err) {
  8964. if (usingObjectURL && img.src) {
  8965. URL.revokeObjectURL(img.src);
  8966. }
  8967. img.removeEventListener("load", loadHandler);
  8968. img.removeEventListener("error", errorHandler);
  8969. Tools.Error("Error while trying to load image: " + input);
  8970. if (onError) {
  8971. onError("Error while trying to load image: " + input, err);
  8972. }
  8973. };
  8974. img.addEventListener("load", loadHandler);
  8975. img.addEventListener("error", errorHandler);
  8976. var noIndexedDB = function () {
  8977. img.src = url;
  8978. };
  8979. var loadFromIndexedDB = function () {
  8980. if (database) {
  8981. database.loadImageFromDB(url, img);
  8982. }
  8983. };
  8984. //ANY database to do!
  8985. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8986. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8987. }
  8988. else {
  8989. if (url.indexOf("file:") !== -1) {
  8990. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8991. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8992. try {
  8993. var blobURL;
  8994. try {
  8995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8996. }
  8997. catch (ex) {
  8998. // Chrome doesn't support oneTimeOnly parameter
  8999. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9000. }
  9001. img.src = blobURL;
  9002. usingObjectURL = true;
  9003. }
  9004. catch (e) {
  9005. img.src = "";
  9006. }
  9007. return img;
  9008. }
  9009. }
  9010. noIndexedDB();
  9011. }
  9012. return img;
  9013. };
  9014. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9015. url = Tools.CleanUrl(url);
  9016. url = Tools.PreprocessUrl(url);
  9017. // If file and file input are set
  9018. if (url.indexOf("file:") !== -1) {
  9019. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9020. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9021. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9022. }
  9023. }
  9024. var loadUrl = Tools.BaseUrl + url;
  9025. var aborted = false;
  9026. var fileRequest = {
  9027. onCompleteObservable: new BABYLON.Observable(),
  9028. abort: function () { return aborted = true; },
  9029. };
  9030. var requestFile = function () {
  9031. var request = new XMLHttpRequest();
  9032. var retryHandle = null;
  9033. fileRequest.abort = function () {
  9034. aborted = true;
  9035. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9036. request.abort();
  9037. }
  9038. if (retryHandle !== null) {
  9039. clearTimeout(retryHandle);
  9040. retryHandle = null;
  9041. }
  9042. };
  9043. var retryLoop = function (retryIndex) {
  9044. request.open('GET', loadUrl, true);
  9045. if (useArrayBuffer) {
  9046. request.responseType = "arraybuffer";
  9047. }
  9048. if (onProgress) {
  9049. request.addEventListener("progress", onProgress);
  9050. }
  9051. var onLoadEnd = function () {
  9052. request.removeEventListener("loadend", onLoadEnd);
  9053. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9054. fileRequest.onCompleteObservable.clear();
  9055. };
  9056. request.addEventListener("loadend", onLoadEnd);
  9057. var onReadyStateChange = function () {
  9058. if (aborted) {
  9059. return;
  9060. }
  9061. // In case of undefined state in some browsers.
  9062. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9063. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9064. request.removeEventListener("readystatechange", onReadyStateChange);
  9065. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9066. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9067. return;
  9068. }
  9069. var retryStrategy = Tools.DefaultRetryStrategy;
  9070. if (retryStrategy) {
  9071. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9072. if (waitTime !== -1) {
  9073. // Prevent the request from completing for retry.
  9074. request.removeEventListener("loadend", onLoadEnd);
  9075. request = new XMLHttpRequest();
  9076. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9077. return;
  9078. }
  9079. }
  9080. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9081. if (onError) {
  9082. onError(request, e);
  9083. }
  9084. else {
  9085. throw e;
  9086. }
  9087. }
  9088. };
  9089. request.addEventListener("readystatechange", onReadyStateChange);
  9090. request.send();
  9091. };
  9092. retryLoop(0);
  9093. };
  9094. // Caching all files
  9095. if (database && database.enableSceneOffline) {
  9096. var noIndexedDB_1 = function () {
  9097. if (!aborted) {
  9098. requestFile();
  9099. }
  9100. };
  9101. var loadFromIndexedDB = function () {
  9102. // TODO: database needs to support aborting and should return a IFileRequest
  9103. if (aborted) {
  9104. return;
  9105. }
  9106. if (database) {
  9107. database.loadFileFromDB(url, function (data) {
  9108. if (!aborted) {
  9109. onSuccess(data);
  9110. }
  9111. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9112. }, onProgress ? function (event) {
  9113. if (!aborted) {
  9114. onProgress(event);
  9115. }
  9116. } : undefined, noIndexedDB_1, useArrayBuffer);
  9117. }
  9118. };
  9119. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9120. }
  9121. else {
  9122. requestFile();
  9123. }
  9124. return fileRequest;
  9125. };
  9126. /**
  9127. * Load a script (identified by an url). When the url returns, the
  9128. * content of this file is added into a new script element, attached to the DOM (body element)
  9129. */
  9130. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9131. var head = document.getElementsByTagName('head')[0];
  9132. var script = document.createElement('script');
  9133. script.type = 'text/javascript';
  9134. script.src = scriptUrl;
  9135. script.onload = function () {
  9136. if (onSuccess) {
  9137. onSuccess();
  9138. }
  9139. };
  9140. script.onerror = function (e) {
  9141. if (onError) {
  9142. onError("Unable to load script '" + scriptUrl + "'", e);
  9143. }
  9144. };
  9145. head.appendChild(script);
  9146. };
  9147. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9148. var reader = new FileReader();
  9149. var request = {
  9150. onCompleteObservable: new BABYLON.Observable(),
  9151. abort: function () { return reader.abort(); },
  9152. };
  9153. reader.onloadend = function (e) {
  9154. request.onCompleteObservable.notifyObservers(request);
  9155. };
  9156. reader.onload = function (e) {
  9157. //target doesn't have result from ts 1.3
  9158. callback(e.target['result']);
  9159. };
  9160. reader.onprogress = progressCallback;
  9161. reader.readAsDataURL(fileToLoad);
  9162. return request;
  9163. };
  9164. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9165. var reader = new FileReader();
  9166. var request = {
  9167. onCompleteObservable: new BABYLON.Observable(),
  9168. abort: function () { return reader.abort(); },
  9169. };
  9170. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9171. reader.onerror = function (e) {
  9172. Tools.Log("Error while reading file: " + fileToLoad.name);
  9173. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9174. };
  9175. reader.onload = function (e) {
  9176. //target doesn't have result from ts 1.3
  9177. callback(e.target['result']);
  9178. };
  9179. if (progressCallBack) {
  9180. reader.onprogress = progressCallBack;
  9181. }
  9182. if (!useArrayBuffer) {
  9183. // Asynchronous read
  9184. reader.readAsText(fileToLoad);
  9185. }
  9186. else {
  9187. reader.readAsArrayBuffer(fileToLoad);
  9188. }
  9189. return request;
  9190. };
  9191. //returns a downloadable url to a file content.
  9192. Tools.FileAsURL = function (content) {
  9193. var fileBlob = new Blob([content]);
  9194. var url = window.URL || window.webkitURL;
  9195. var link = url.createObjectURL(fileBlob);
  9196. return link;
  9197. };
  9198. // Misc.
  9199. Tools.Format = function (value, decimals) {
  9200. if (decimals === void 0) { decimals = 2; }
  9201. return value.toFixed(decimals);
  9202. };
  9203. Tools.CheckExtends = function (v, min, max) {
  9204. if (v.x < min.x)
  9205. min.x = v.x;
  9206. if (v.y < min.y)
  9207. min.y = v.y;
  9208. if (v.z < min.z)
  9209. min.z = v.z;
  9210. if (v.x > max.x)
  9211. max.x = v.x;
  9212. if (v.y > max.y)
  9213. max.y = v.y;
  9214. if (v.z > max.z)
  9215. max.z = v.z;
  9216. };
  9217. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9218. for (var prop in source) {
  9219. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9220. continue;
  9221. }
  9222. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9223. continue;
  9224. }
  9225. var sourceValue = source[prop];
  9226. var typeOfSourceValue = typeof sourceValue;
  9227. if (typeOfSourceValue === "function") {
  9228. continue;
  9229. }
  9230. try {
  9231. if (typeOfSourceValue === "object") {
  9232. if (sourceValue instanceof Array) {
  9233. destination[prop] = [];
  9234. if (sourceValue.length > 0) {
  9235. if (typeof sourceValue[0] == "object") {
  9236. for (var index = 0; index < sourceValue.length; index++) {
  9237. var clonedValue = cloneValue(sourceValue[index], destination);
  9238. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9239. destination[prop].push(clonedValue);
  9240. }
  9241. }
  9242. }
  9243. else {
  9244. destination[prop] = sourceValue.slice(0);
  9245. }
  9246. }
  9247. }
  9248. else {
  9249. destination[prop] = cloneValue(sourceValue, destination);
  9250. }
  9251. }
  9252. else {
  9253. destination[prop] = sourceValue;
  9254. }
  9255. }
  9256. catch (e) {
  9257. // Just ignore error (it could be because of a read-only property)
  9258. }
  9259. }
  9260. };
  9261. Tools.IsEmpty = function (obj) {
  9262. for (var i in obj) {
  9263. if (obj.hasOwnProperty(i)) {
  9264. return false;
  9265. }
  9266. }
  9267. return true;
  9268. };
  9269. Tools.RegisterTopRootEvents = function (events) {
  9270. for (var index = 0; index < events.length; index++) {
  9271. var event = events[index];
  9272. window.addEventListener(event.name, event.handler, false);
  9273. try {
  9274. if (window.parent) {
  9275. window.parent.addEventListener(event.name, event.handler, false);
  9276. }
  9277. }
  9278. catch (e) {
  9279. // Silently fails...
  9280. }
  9281. }
  9282. };
  9283. Tools.UnregisterTopRootEvents = function (events) {
  9284. for (var index = 0; index < events.length; index++) {
  9285. var event = events[index];
  9286. window.removeEventListener(event.name, event.handler);
  9287. try {
  9288. if (window.parent) {
  9289. window.parent.removeEventListener(event.name, event.handler);
  9290. }
  9291. }
  9292. catch (e) {
  9293. // Silently fails...
  9294. }
  9295. }
  9296. };
  9297. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9298. if (mimeType === void 0) { mimeType = "image/png"; }
  9299. // Read the contents of the framebuffer
  9300. var numberOfChannelsByLine = width * 4;
  9301. var halfHeight = height / 2;
  9302. //Reading datas from WebGL
  9303. var data = engine.readPixels(0, 0, width, height);
  9304. //To flip image on Y axis.
  9305. for (var i = 0; i < halfHeight; i++) {
  9306. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9307. var currentCell = j + i * numberOfChannelsByLine;
  9308. var targetLine = height - i - 1;
  9309. var targetCell = j + targetLine * numberOfChannelsByLine;
  9310. var temp = data[currentCell];
  9311. data[currentCell] = data[targetCell];
  9312. data[targetCell] = temp;
  9313. }
  9314. }
  9315. // Create a 2D canvas to store the result
  9316. if (!screenshotCanvas) {
  9317. screenshotCanvas = document.createElement('canvas');
  9318. }
  9319. screenshotCanvas.width = width;
  9320. screenshotCanvas.height = height;
  9321. var context = screenshotCanvas.getContext('2d');
  9322. if (context) {
  9323. // Copy the pixels to a 2D canvas
  9324. var imageData = context.createImageData(width, height);
  9325. var castData = (imageData.data);
  9326. castData.set(data);
  9327. context.putImageData(imageData, 0, 0);
  9328. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9329. }
  9330. };
  9331. /**
  9332. * Converts the canvas data to blob.
  9333. * This acts as a polyfill for browsers not supporting the to blob function.
  9334. * @param canvas Defines the canvas to extract the data from
  9335. * @param successCallback Defines the callback triggered once the data are available
  9336. * @param mimeType Defines the mime type of the result
  9337. */
  9338. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9339. if (mimeType === void 0) { mimeType = "image/png"; }
  9340. // We need HTMLCanvasElement.toBlob for HD screenshots
  9341. if (!canvas.toBlob) {
  9342. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9343. canvas.toBlob = function (callback, type, quality) {
  9344. var _this = this;
  9345. setTimeout(function () {
  9346. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9347. for (var i = 0; i < len; i++) {
  9348. arr[i] = binStr.charCodeAt(i);
  9349. }
  9350. callback(new Blob([arr]));
  9351. });
  9352. };
  9353. }
  9354. canvas.toBlob(function (blob) {
  9355. successCallback(blob);
  9356. }, mimeType);
  9357. };
  9358. /**
  9359. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9360. * @param successCallback Defines the callback triggered once the data are available
  9361. * @param mimeType Defines the mime type of the result
  9362. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9363. */
  9364. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9365. if (mimeType === void 0) { mimeType = "image/png"; }
  9366. if (successCallback) {
  9367. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9368. successCallback(base64Image);
  9369. }
  9370. else {
  9371. this.ToBlob(screenshotCanvas, function (blob) {
  9372. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9373. if (("download" in document.createElement("a"))) {
  9374. if (!fileName) {
  9375. var date = new Date();
  9376. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9377. fileName = "screenshot_" + stringDate + ".png";
  9378. }
  9379. Tools.Download(blob, fileName);
  9380. }
  9381. else {
  9382. var url = URL.createObjectURL(blob);
  9383. var newWindow = window.open("");
  9384. if (!newWindow)
  9385. return;
  9386. var img = newWindow.document.createElement("img");
  9387. img.onload = function () {
  9388. // no longer need to read the blob so it's revoked
  9389. URL.revokeObjectURL(url);
  9390. };
  9391. img.src = url;
  9392. newWindow.document.body.appendChild(img);
  9393. }
  9394. }, mimeType);
  9395. }
  9396. };
  9397. /**
  9398. * Downloads a blob in the browser
  9399. * @param blob defines the blob to download
  9400. * @param fileName defines the name of the downloaded file
  9401. */
  9402. Tools.Download = function (blob, fileName) {
  9403. var url = window.URL.createObjectURL(blob);
  9404. var a = document.createElement("a");
  9405. document.body.appendChild(a);
  9406. a.style.display = "none";
  9407. a.href = url;
  9408. a.download = fileName;
  9409. a.addEventListener("click", function () {
  9410. if (a.parentElement) {
  9411. a.parentElement.removeChild(a);
  9412. }
  9413. });
  9414. a.click();
  9415. window.URL.revokeObjectURL(url);
  9416. };
  9417. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9418. if (mimeType === void 0) { mimeType = "image/png"; }
  9419. var width;
  9420. var height;
  9421. // If a precision value is specified
  9422. if (size.precision) {
  9423. width = Math.round(engine.getRenderWidth() * size.precision);
  9424. height = Math.round(width / engine.getAspectRatio(camera));
  9425. }
  9426. else if (size.width && size.height) {
  9427. width = size.width;
  9428. height = size.height;
  9429. }
  9430. //If passing only width, computing height to keep display canvas ratio.
  9431. else if (size.width && !size.height) {
  9432. width = size.width;
  9433. height = Math.round(width / engine.getAspectRatio(camera));
  9434. }
  9435. //If passing only height, computing width to keep display canvas ratio.
  9436. else if (size.height && !size.width) {
  9437. height = size.height;
  9438. width = Math.round(height * engine.getAspectRatio(camera));
  9439. }
  9440. //Assuming here that "size" parameter is a number
  9441. else if (!isNaN(size)) {
  9442. height = size;
  9443. width = size;
  9444. }
  9445. else {
  9446. Tools.Error("Invalid 'size' parameter !");
  9447. return;
  9448. }
  9449. if (!screenshotCanvas) {
  9450. screenshotCanvas = document.createElement('canvas');
  9451. }
  9452. screenshotCanvas.width = width;
  9453. screenshotCanvas.height = height;
  9454. var renderContext = screenshotCanvas.getContext("2d");
  9455. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9456. var newWidth = width;
  9457. var newHeight = newWidth / ratio;
  9458. if (newHeight > height) {
  9459. newHeight = height;
  9460. newWidth = newHeight * ratio;
  9461. }
  9462. var offsetX = Math.max(0, width - newWidth) / 2;
  9463. var offsetY = Math.max(0, height - newHeight) / 2;
  9464. var renderingCanvas = engine.getRenderingCanvas();
  9465. if (renderContext && renderingCanvas) {
  9466. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9467. }
  9468. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9469. };
  9470. /**
  9471. * Generates an image screenshot from the specified camera.
  9472. *
  9473. * @param engine The engine to use for rendering
  9474. * @param camera The camera to use for rendering
  9475. * @param size This parameter can be set to a single number or to an object with the
  9476. * following (optional) properties: precision, width, height. If a single number is passed,
  9477. * it will be used for both width and height. If an object is passed, the screenshot size
  9478. * will be derived from the parameters. The precision property is a multiplier allowing
  9479. * rendering at a higher or lower resolution.
  9480. * @param successCallback The callback receives a single parameter which contains the
  9481. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9482. * src parameter of an <img> to display it.
  9483. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9484. * Check your browser for supported MIME types.
  9485. * @param samples Texture samples (default: 1)
  9486. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9487. * @param fileName A name for for the downloaded file.
  9488. * @constructor
  9489. */
  9490. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9491. if (mimeType === void 0) { mimeType = "image/png"; }
  9492. if (samples === void 0) { samples = 1; }
  9493. if (antialiasing === void 0) { antialiasing = false; }
  9494. var width;
  9495. var height;
  9496. //If a precision value is specified
  9497. if (size.precision) {
  9498. width = Math.round(engine.getRenderWidth() * size.precision);
  9499. height = Math.round(width / engine.getAspectRatio(camera));
  9500. size = { width: width, height: height };
  9501. }
  9502. else if (size.width && size.height) {
  9503. width = size.width;
  9504. height = size.height;
  9505. }
  9506. //If passing only width, computing height to keep display canvas ratio.
  9507. else if (size.width && !size.height) {
  9508. width = size.width;
  9509. height = Math.round(width / engine.getAspectRatio(camera));
  9510. size = { width: width, height: height };
  9511. }
  9512. //If passing only height, computing width to keep display canvas ratio.
  9513. else if (size.height && !size.width) {
  9514. height = size.height;
  9515. width = Math.round(height * engine.getAspectRatio(camera));
  9516. size = { width: width, height: height };
  9517. }
  9518. //Assuming here that "size" parameter is a number
  9519. else if (!isNaN(size)) {
  9520. height = size;
  9521. width = size;
  9522. }
  9523. else {
  9524. Tools.Error("Invalid 'size' parameter !");
  9525. return;
  9526. }
  9527. var scene = camera.getScene();
  9528. var previousCamera = null;
  9529. if (scene.activeCamera !== camera) {
  9530. previousCamera = scene.activeCamera;
  9531. scene.activeCamera = camera;
  9532. }
  9533. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9534. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9535. texture.renderList = null;
  9536. texture.samples = samples;
  9537. if (antialiasing) {
  9538. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9539. }
  9540. texture.onAfterRenderObservable.add(function () {
  9541. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9542. });
  9543. scene.incrementRenderId();
  9544. scene.resetCachedMaterial();
  9545. texture.render(true);
  9546. texture.dispose();
  9547. if (previousCamera) {
  9548. scene.activeCamera = previousCamera;
  9549. }
  9550. camera.getProjectionMatrix(true); // Force cache refresh;
  9551. };
  9552. // XHR response validator for local file scenario
  9553. Tools.ValidateXHRData = function (xhr, dataType) {
  9554. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9555. if (dataType === void 0) { dataType = 7; }
  9556. try {
  9557. if (dataType & 1) {
  9558. if (xhr.responseText && xhr.responseText.length > 0) {
  9559. return true;
  9560. }
  9561. else if (dataType === 1) {
  9562. return false;
  9563. }
  9564. }
  9565. if (dataType & 2) {
  9566. // Check header width and height since there is no "TGA" magic number
  9567. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9568. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9569. return true;
  9570. }
  9571. else if (dataType === 2) {
  9572. return false;
  9573. }
  9574. }
  9575. if (dataType & 4) {
  9576. // Check for the "DDS" magic number
  9577. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9578. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9579. return true;
  9580. }
  9581. else {
  9582. return false;
  9583. }
  9584. }
  9585. }
  9586. catch (e) {
  9587. // Global protection
  9588. }
  9589. return false;
  9590. };
  9591. /**
  9592. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9593. * Be aware Math.random() could cause collisions, but:
  9594. * "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"
  9595. */
  9596. Tools.RandomId = function () {
  9597. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9598. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9599. return v.toString(16);
  9600. });
  9601. };
  9602. /**
  9603. * Test if the given uri is a base64 string.
  9604. * @param uri The uri to test
  9605. * @return True if the uri is a base64 string or false otherwise.
  9606. */
  9607. Tools.IsBase64 = function (uri) {
  9608. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9609. };
  9610. /**
  9611. * Decode the given base64 uri.
  9612. * @param uri The uri to decode
  9613. * @return The decoded base64 data.
  9614. */
  9615. Tools.DecodeBase64 = function (uri) {
  9616. var decodedString = atob(uri.split(",")[1]);
  9617. var bufferLength = decodedString.length;
  9618. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9619. for (var i = 0; i < bufferLength; i++) {
  9620. bufferView[i] = decodedString.charCodeAt(i);
  9621. }
  9622. return bufferView.buffer;
  9623. };
  9624. Object.defineProperty(Tools, "NoneLogLevel", {
  9625. get: function () {
  9626. return Tools._NoneLogLevel;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(Tools, "MessageLogLevel", {
  9632. get: function () {
  9633. return Tools._MessageLogLevel;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Tools, "WarningLogLevel", {
  9639. get: function () {
  9640. return Tools._WarningLogLevel;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Tools, "ErrorLogLevel", {
  9646. get: function () {
  9647. return Tools._ErrorLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "AllLogLevel", {
  9653. get: function () {
  9654. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Tools._AddLogEntry = function (entry) {
  9660. Tools._LogCache = entry + Tools._LogCache;
  9661. if (Tools.OnNewCacheEntry) {
  9662. Tools.OnNewCacheEntry(entry);
  9663. }
  9664. };
  9665. Tools._FormatMessage = function (message) {
  9666. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9667. var date = new Date();
  9668. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9669. };
  9670. Tools._LogDisabled = function (message) {
  9671. // nothing to do
  9672. };
  9673. Tools._LogEnabled = function (message) {
  9674. var formattedMessage = Tools._FormatMessage(message);
  9675. console.log("BJS - " + formattedMessage);
  9676. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9677. Tools._AddLogEntry(entry);
  9678. };
  9679. Tools._WarnDisabled = function (message) {
  9680. // nothing to do
  9681. };
  9682. Tools._WarnEnabled = function (message) {
  9683. var formattedMessage = Tools._FormatMessage(message);
  9684. console.warn("BJS - " + formattedMessage);
  9685. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9686. Tools._AddLogEntry(entry);
  9687. };
  9688. Tools._ErrorDisabled = function (message) {
  9689. // nothing to do
  9690. };
  9691. Tools._ErrorEnabled = function (message) {
  9692. Tools.errorsCount++;
  9693. var formattedMessage = Tools._FormatMessage(message);
  9694. console.error("BJS - " + formattedMessage);
  9695. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9696. Tools._AddLogEntry(entry);
  9697. };
  9698. Object.defineProperty(Tools, "LogCache", {
  9699. get: function () {
  9700. return Tools._LogCache;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Tools.ClearLogCache = function () {
  9706. Tools._LogCache = "";
  9707. Tools.errorsCount = 0;
  9708. };
  9709. Object.defineProperty(Tools, "LogLevels", {
  9710. set: function (level) {
  9711. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9712. Tools.Log = Tools._LogEnabled;
  9713. }
  9714. else {
  9715. Tools.Log = Tools._LogDisabled;
  9716. }
  9717. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9718. Tools.Warn = Tools._WarnEnabled;
  9719. }
  9720. else {
  9721. Tools.Warn = Tools._WarnDisabled;
  9722. }
  9723. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9724. Tools.Error = Tools._ErrorEnabled;
  9725. }
  9726. else {
  9727. Tools.Error = Tools._ErrorDisabled;
  9728. }
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Tools.IsWindowObjectExist = function () {
  9734. return (typeof window) !== "undefined";
  9735. };
  9736. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9737. get: function () {
  9738. return Tools._PerformanceNoneLogLevel;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9744. get: function () {
  9745. return Tools._PerformanceUserMarkLogLevel;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9751. get: function () {
  9752. return Tools._PerformanceConsoleLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9758. set: function (level) {
  9759. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9760. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9761. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9762. return;
  9763. }
  9764. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9765. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9766. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9767. return;
  9768. }
  9769. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9770. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9776. };
  9777. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9778. };
  9779. Tools._StartUserMark = function (counterName, condition) {
  9780. if (condition === void 0) { condition = true; }
  9781. if (!Tools._performance) {
  9782. if (!Tools.IsWindowObjectExist()) {
  9783. return;
  9784. }
  9785. Tools._performance = window.performance;
  9786. }
  9787. if (!condition || !Tools._performance.mark) {
  9788. return;
  9789. }
  9790. Tools._performance.mark(counterName + "-Begin");
  9791. };
  9792. Tools._EndUserMark = function (counterName, condition) {
  9793. if (condition === void 0) { condition = true; }
  9794. if (!condition || !Tools._performance.mark) {
  9795. return;
  9796. }
  9797. Tools._performance.mark(counterName + "-End");
  9798. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9799. };
  9800. Tools._StartPerformanceConsole = function (counterName, condition) {
  9801. if (condition === void 0) { condition = true; }
  9802. if (!condition) {
  9803. return;
  9804. }
  9805. Tools._StartUserMark(counterName, condition);
  9806. if (console.time) {
  9807. console.time(counterName);
  9808. }
  9809. };
  9810. Tools._EndPerformanceConsole = function (counterName, condition) {
  9811. if (condition === void 0) { condition = true; }
  9812. if (!condition) {
  9813. return;
  9814. }
  9815. Tools._EndUserMark(counterName, condition);
  9816. if (console.time) {
  9817. console.timeEnd(counterName);
  9818. }
  9819. };
  9820. Object.defineProperty(Tools, "Now", {
  9821. get: function () {
  9822. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9823. return window.performance.now();
  9824. }
  9825. return Date.now();
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. /**
  9831. * This method will return the name of the class used to create the instance of the given object.
  9832. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9833. * @param object the object to get the class name from
  9834. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9835. */
  9836. Tools.GetClassName = function (object, isType) {
  9837. if (isType === void 0) { isType = false; }
  9838. var name = null;
  9839. if (!isType && object.getClassName) {
  9840. name = object.getClassName();
  9841. }
  9842. else {
  9843. if (object instanceof Object) {
  9844. var classObj = isType ? object : Object.getPrototypeOf(object);
  9845. name = classObj.constructor["__bjsclassName__"];
  9846. }
  9847. if (!name) {
  9848. name = typeof object;
  9849. }
  9850. }
  9851. return name;
  9852. };
  9853. Tools.First = function (array, predicate) {
  9854. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9855. var el = array_1[_i];
  9856. if (predicate(el)) {
  9857. return el;
  9858. }
  9859. }
  9860. return null;
  9861. };
  9862. /**
  9863. * This method will return the name of the full name of the class, including its owning module (if any).
  9864. * 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).
  9865. * @param object the object to get the class name from
  9866. * @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.
  9867. */
  9868. Tools.getFullClassName = function (object, isType) {
  9869. if (isType === void 0) { isType = false; }
  9870. var className = null;
  9871. var moduleName = null;
  9872. if (!isType && object.getClassName) {
  9873. className = object.getClassName();
  9874. }
  9875. else {
  9876. if (object instanceof Object) {
  9877. var classObj = isType ? object : Object.getPrototypeOf(object);
  9878. className = classObj.constructor["__bjsclassName__"];
  9879. moduleName = classObj.constructor["__bjsmoduleName__"];
  9880. }
  9881. if (!className) {
  9882. className = typeof object;
  9883. }
  9884. }
  9885. if (!className) {
  9886. return null;
  9887. }
  9888. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9889. };
  9890. /**
  9891. * 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.
  9892. * @param array
  9893. */
  9894. Tools.arrayOrStringFeeder = function (array) {
  9895. return function (index) {
  9896. if (index >= array.length) {
  9897. return null;
  9898. }
  9899. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9900. if (val && val.getHashCode) {
  9901. val = val.getHashCode();
  9902. }
  9903. if (typeof val === "string") {
  9904. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9905. }
  9906. return val;
  9907. };
  9908. };
  9909. /**
  9910. * Compute the hashCode of a stream of number
  9911. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9912. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9913. * @return the hash code computed
  9914. */
  9915. Tools.hashCodeFromStream = function (feeder) {
  9916. // Based from here: http://stackoverflow.com/a/7616484/802124
  9917. var hash = 0;
  9918. var index = 0;
  9919. var chr = feeder(index++);
  9920. while (chr != null) {
  9921. hash = ((hash << 5) - hash) + chr;
  9922. hash |= 0; // Convert to 32bit integer
  9923. chr = feeder(index++);
  9924. }
  9925. return hash;
  9926. };
  9927. /**
  9928. * Returns a promise that resolves after the given amount of time.
  9929. * @param delay Number of milliseconds to delay
  9930. * @returns Promise that resolves after the given amount of time
  9931. */
  9932. Tools.DelayAsync = function (delay) {
  9933. return new Promise(function (resolve) {
  9934. setTimeout(function () {
  9935. resolve();
  9936. }, delay);
  9937. });
  9938. };
  9939. /**
  9940. * Gets the current gradient from an array of IValueGradient
  9941. * @param ratio defines the current ratio to get
  9942. * @param gradients defines the array of IValueGradient
  9943. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9944. */
  9945. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9946. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9947. var currentGradient = gradients[gradientIndex];
  9948. var nextGradient = gradients[gradientIndex + 1];
  9949. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9950. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9951. updateFunc(currentGradient, nextGradient, scale);
  9952. }
  9953. }
  9954. };
  9955. Tools.BaseUrl = "";
  9956. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9957. /**
  9958. * Default behaviour for cors in the application.
  9959. * It can be a string if the expected behavior is identical in the entire app.
  9960. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9961. */
  9962. Tools.CorsBehavior = "anonymous";
  9963. Tools.UseFallbackTexture = true;
  9964. /**
  9965. * Use this object to register external classes like custom textures or material
  9966. * to allow the laoders to instantiate them
  9967. */
  9968. Tools.RegisteredExternalClasses = {};
  9969. // Used in case of a texture loading problem
  9970. 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";
  9971. Tools._tmpFloatArray = new Float32Array(1);
  9972. Tools.PreprocessUrl = function (url) {
  9973. return url;
  9974. };
  9975. // Logs
  9976. Tools._NoneLogLevel = 0;
  9977. Tools._MessageLogLevel = 1;
  9978. Tools._WarningLogLevel = 2;
  9979. Tools._ErrorLogLevel = 4;
  9980. Tools._LogCache = "";
  9981. Tools.errorsCount = 0;
  9982. Tools.Log = Tools._LogEnabled;
  9983. Tools.Warn = Tools._WarnEnabled;
  9984. Tools.Error = Tools._ErrorEnabled;
  9985. // Performances
  9986. Tools._PerformanceNoneLogLevel = 0;
  9987. Tools._PerformanceUserMarkLogLevel = 1;
  9988. Tools._PerformanceConsoleLogLevel = 2;
  9989. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9990. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9991. return Tools;
  9992. }());
  9993. BABYLON.Tools = Tools;
  9994. /**
  9995. * This class is used to track a performance counter which is number based.
  9996. * The user has access to many properties which give statistics of different nature
  9997. *
  9998. * The implementer can track two kinds of Performance Counter: time and count
  9999. * 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.
  10000. * 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.
  10001. */
  10002. var PerfCounter = /** @class */ (function () {
  10003. function PerfCounter() {
  10004. this._startMonitoringTime = 0;
  10005. this._min = 0;
  10006. this._max = 0;
  10007. this._average = 0;
  10008. this._lastSecAverage = 0;
  10009. this._current = 0;
  10010. this._totalValueCount = 0;
  10011. this._totalAccumulated = 0;
  10012. this._lastSecAccumulated = 0;
  10013. this._lastSecTime = 0;
  10014. this._lastSecValueCount = 0;
  10015. }
  10016. Object.defineProperty(PerfCounter.prototype, "min", {
  10017. /**
  10018. * Returns the smallest value ever
  10019. */
  10020. get: function () {
  10021. return this._min;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Object.defineProperty(PerfCounter.prototype, "max", {
  10027. /**
  10028. * Returns the biggest value ever
  10029. */
  10030. get: function () {
  10031. return this._max;
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. Object.defineProperty(PerfCounter.prototype, "average", {
  10037. /**
  10038. * Returns the average value since the performance counter is running
  10039. */
  10040. get: function () {
  10041. return this._average;
  10042. },
  10043. enumerable: true,
  10044. configurable: true
  10045. });
  10046. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10047. /**
  10048. * Returns the average value of the last second the counter was monitored
  10049. */
  10050. get: function () {
  10051. return this._lastSecAverage;
  10052. },
  10053. enumerable: true,
  10054. configurable: true
  10055. });
  10056. Object.defineProperty(PerfCounter.prototype, "current", {
  10057. /**
  10058. * Returns the current value
  10059. */
  10060. get: function () {
  10061. return this._current;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(PerfCounter.prototype, "total", {
  10067. get: function () {
  10068. return this._totalAccumulated;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(PerfCounter.prototype, "count", {
  10074. get: function () {
  10075. return this._totalValueCount;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. /**
  10081. * Call this method to start monitoring a new frame.
  10082. * 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.
  10083. */
  10084. PerfCounter.prototype.fetchNewFrame = function () {
  10085. this._totalValueCount++;
  10086. this._current = 0;
  10087. this._lastSecValueCount++;
  10088. };
  10089. /**
  10090. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10091. * @param newCount the count value to add to the monitored count
  10092. * @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.
  10093. */
  10094. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10095. if (!PerfCounter.Enabled) {
  10096. return;
  10097. }
  10098. this._current += newCount;
  10099. if (fetchResult) {
  10100. this._fetchResult();
  10101. }
  10102. };
  10103. /**
  10104. * Start monitoring this performance counter
  10105. */
  10106. PerfCounter.prototype.beginMonitoring = function () {
  10107. if (!PerfCounter.Enabled) {
  10108. return;
  10109. }
  10110. this._startMonitoringTime = Tools.Now;
  10111. };
  10112. /**
  10113. * Compute the time lapsed since the previous beginMonitoring() call.
  10114. * @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
  10115. */
  10116. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10117. if (newFrame === void 0) { newFrame = true; }
  10118. if (!PerfCounter.Enabled) {
  10119. return;
  10120. }
  10121. if (newFrame) {
  10122. this.fetchNewFrame();
  10123. }
  10124. var currentTime = Tools.Now;
  10125. this._current = currentTime - this._startMonitoringTime;
  10126. if (newFrame) {
  10127. this._fetchResult();
  10128. }
  10129. };
  10130. PerfCounter.prototype._fetchResult = function () {
  10131. this._totalAccumulated += this._current;
  10132. this._lastSecAccumulated += this._current;
  10133. // Min/Max update
  10134. this._min = Math.min(this._min, this._current);
  10135. this._max = Math.max(this._max, this._current);
  10136. this._average = this._totalAccumulated / this._totalValueCount;
  10137. // Reset last sec?
  10138. var now = Tools.Now;
  10139. if ((now - this._lastSecTime) > 1000) {
  10140. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10141. this._lastSecTime = now;
  10142. this._lastSecAccumulated = 0;
  10143. this._lastSecValueCount = 0;
  10144. }
  10145. };
  10146. PerfCounter.Enabled = true;
  10147. return PerfCounter;
  10148. }());
  10149. BABYLON.PerfCounter = PerfCounter;
  10150. /**
  10151. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10152. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10153. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10154. * @param name The name of the class, case should be preserved
  10155. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10156. */
  10157. function className(name, module) {
  10158. return function (target) {
  10159. target["__bjsclassName__"] = name;
  10160. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10161. };
  10162. }
  10163. BABYLON.className = className;
  10164. /**
  10165. * An implementation of a loop for asynchronous functions.
  10166. */
  10167. var AsyncLoop = /** @class */ (function () {
  10168. /**
  10169. * Constroctor.
  10170. * @param iterations the number of iterations.
  10171. * @param _fn the function to run each iteration
  10172. * @param _successCallback the callback that will be called upon succesful execution
  10173. * @param offset starting offset.
  10174. */
  10175. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10176. if (offset === void 0) { offset = 0; }
  10177. this.iterations = iterations;
  10178. this._fn = _fn;
  10179. this._successCallback = _successCallback;
  10180. this.index = offset - 1;
  10181. this._done = false;
  10182. }
  10183. /**
  10184. * Execute the next iteration. Must be called after the last iteration was finished.
  10185. */
  10186. AsyncLoop.prototype.executeNext = function () {
  10187. if (!this._done) {
  10188. if (this.index + 1 < this.iterations) {
  10189. ++this.index;
  10190. this._fn(this);
  10191. }
  10192. else {
  10193. this.breakLoop();
  10194. }
  10195. }
  10196. };
  10197. /**
  10198. * Break the loop and run the success callback.
  10199. */
  10200. AsyncLoop.prototype.breakLoop = function () {
  10201. this._done = true;
  10202. this._successCallback();
  10203. };
  10204. /**
  10205. * Helper function
  10206. */
  10207. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10208. if (offset === void 0) { offset = 0; }
  10209. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10210. loop.executeNext();
  10211. return loop;
  10212. };
  10213. /**
  10214. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10215. * @param iterations total number of iterations
  10216. * @param syncedIterations number of synchronous iterations in each async iteration.
  10217. * @param fn the function to call each iteration.
  10218. * @param callback a success call back that will be called when iterating stops.
  10219. * @param breakFunction a break condition (optional)
  10220. * @param timeout timeout settings for the setTimeout function. default - 0.
  10221. * @constructor
  10222. */
  10223. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10224. if (timeout === void 0) { timeout = 0; }
  10225. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10226. if (breakFunction && breakFunction())
  10227. loop.breakLoop();
  10228. else {
  10229. setTimeout(function () {
  10230. for (var i = 0; i < syncedIterations; ++i) {
  10231. var iteration = (loop.index * syncedIterations) + i;
  10232. if (iteration >= iterations)
  10233. break;
  10234. fn(iteration);
  10235. if (breakFunction && breakFunction()) {
  10236. loop.breakLoop();
  10237. break;
  10238. }
  10239. }
  10240. loop.executeNext();
  10241. }, timeout);
  10242. }
  10243. }, callback);
  10244. };
  10245. return AsyncLoop;
  10246. }());
  10247. BABYLON.AsyncLoop = AsyncLoop;
  10248. })(BABYLON || (BABYLON = {}));
  10249. //# sourceMappingURL=babylon.tools.js.map
  10250. var BABYLON;
  10251. (function (BABYLON) {
  10252. var PromiseStates;
  10253. (function (PromiseStates) {
  10254. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10255. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10256. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10257. })(PromiseStates || (PromiseStates = {}));
  10258. var FulFillmentAgregator = /** @class */ (function () {
  10259. function FulFillmentAgregator() {
  10260. this.count = 0;
  10261. this.target = 0;
  10262. this.results = [];
  10263. }
  10264. return FulFillmentAgregator;
  10265. }());
  10266. var InternalPromise = /** @class */ (function () {
  10267. function InternalPromise(resolver) {
  10268. var _this = this;
  10269. this._state = PromiseStates.Pending;
  10270. this._children = new Array();
  10271. this._rejectWasConsumed = false;
  10272. if (!resolver) {
  10273. return;
  10274. }
  10275. try {
  10276. resolver(function (value) {
  10277. _this._resolve(value);
  10278. }, function (reason) {
  10279. _this._reject(reason);
  10280. });
  10281. }
  10282. catch (e) {
  10283. this._reject(e);
  10284. }
  10285. }
  10286. Object.defineProperty(InternalPromise.prototype, "_result", {
  10287. get: function () {
  10288. return this._resultValue;
  10289. },
  10290. set: function (value) {
  10291. this._resultValue = value;
  10292. if (this._parent && this._parent._result === undefined) {
  10293. this._parent._result = value;
  10294. }
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. InternalPromise.prototype.catch = function (onRejected) {
  10300. return this.then(undefined, onRejected);
  10301. };
  10302. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10303. var _this = this;
  10304. var newPromise = new InternalPromise();
  10305. newPromise._onFulfilled = onFulfilled;
  10306. newPromise._onRejected = onRejected;
  10307. // Composition
  10308. this._children.push(newPromise);
  10309. newPromise._parent = this;
  10310. if (this._state !== PromiseStates.Pending) {
  10311. BABYLON.Tools.SetImmediate(function () {
  10312. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10313. var returnedValue = newPromise._resolve(_this._result);
  10314. if (returnedValue !== undefined && returnedValue !== null) {
  10315. if (returnedValue._state !== undefined) {
  10316. var returnedPromise = returnedValue;
  10317. newPromise._children.push(returnedPromise);
  10318. returnedPromise._parent = newPromise;
  10319. newPromise = returnedPromise;
  10320. }
  10321. else {
  10322. newPromise._result = returnedValue;
  10323. }
  10324. }
  10325. }
  10326. else {
  10327. newPromise._reject(_this._reason);
  10328. }
  10329. });
  10330. }
  10331. return newPromise;
  10332. };
  10333. InternalPromise.prototype._moveChildren = function (children) {
  10334. var _this = this;
  10335. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10336. this._children.forEach(function (child) {
  10337. child._parent = _this;
  10338. });
  10339. if (this._state === PromiseStates.Fulfilled) {
  10340. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10341. var child = _b[_i];
  10342. child._resolve(this._result);
  10343. }
  10344. }
  10345. else if (this._state === PromiseStates.Rejected) {
  10346. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10347. var child = _d[_c];
  10348. child._reject(this._reason);
  10349. }
  10350. }
  10351. var _a;
  10352. };
  10353. InternalPromise.prototype._resolve = function (value) {
  10354. try {
  10355. this._state = PromiseStates.Fulfilled;
  10356. var returnedValue = null;
  10357. if (this._onFulfilled) {
  10358. returnedValue = this._onFulfilled(value);
  10359. }
  10360. if (returnedValue !== undefined && returnedValue !== null) {
  10361. if (returnedValue._state !== undefined) {
  10362. // Transmit children
  10363. var returnedPromise = returnedValue;
  10364. returnedPromise._parent = this;
  10365. returnedPromise._moveChildren(this._children);
  10366. value = returnedPromise._result;
  10367. }
  10368. else {
  10369. value = returnedValue;
  10370. }
  10371. }
  10372. this._result = value;
  10373. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10374. var child = _a[_i];
  10375. child._resolve(value);
  10376. }
  10377. this._children.length = 0;
  10378. delete this._onFulfilled;
  10379. delete this._onRejected;
  10380. }
  10381. catch (e) {
  10382. this._reject(e, true);
  10383. }
  10384. };
  10385. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10386. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10387. this._state = PromiseStates.Rejected;
  10388. this._reason = reason;
  10389. if (this._onRejected && !onLocalThrow) {
  10390. try {
  10391. this._onRejected(reason);
  10392. this._rejectWasConsumed = true;
  10393. }
  10394. catch (e) {
  10395. reason = e;
  10396. }
  10397. }
  10398. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10399. var child = _a[_i];
  10400. if (this._rejectWasConsumed) {
  10401. child._resolve(null);
  10402. }
  10403. else {
  10404. child._reject(reason);
  10405. }
  10406. }
  10407. this._children.length = 0;
  10408. delete this._onFulfilled;
  10409. delete this._onRejected;
  10410. };
  10411. InternalPromise.resolve = function (value) {
  10412. var newPromise = new InternalPromise();
  10413. newPromise._resolve(value);
  10414. return newPromise;
  10415. };
  10416. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10417. promise.then(function (value) {
  10418. agregator.results[index] = value;
  10419. agregator.count++;
  10420. if (agregator.count === agregator.target) {
  10421. agregator.rootPromise._resolve(agregator.results);
  10422. }
  10423. return null;
  10424. }, function (reason) {
  10425. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10426. agregator.rootPromise._reject(reason);
  10427. }
  10428. });
  10429. };
  10430. InternalPromise.all = function (promises) {
  10431. var newPromise = new InternalPromise();
  10432. var agregator = new FulFillmentAgregator();
  10433. agregator.target = promises.length;
  10434. agregator.rootPromise = newPromise;
  10435. if (promises.length) {
  10436. for (var index = 0; index < promises.length; index++) {
  10437. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10438. }
  10439. }
  10440. else {
  10441. newPromise._resolve([]);
  10442. }
  10443. return newPromise;
  10444. };
  10445. InternalPromise.race = function (promises) {
  10446. var newPromise = new InternalPromise();
  10447. if (promises.length) {
  10448. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10449. var promise = promises_1[_i];
  10450. promise.then(function (value) {
  10451. if (newPromise) {
  10452. newPromise._resolve(value);
  10453. newPromise = null;
  10454. }
  10455. return null;
  10456. }, function (reason) {
  10457. if (newPromise) {
  10458. newPromise._reject(reason);
  10459. newPromise = null;
  10460. }
  10461. });
  10462. }
  10463. }
  10464. return newPromise;
  10465. };
  10466. return InternalPromise;
  10467. }());
  10468. /**
  10469. * Helper class that provides a small promise polyfill
  10470. */
  10471. var PromisePolyfill = /** @class */ (function () {
  10472. function PromisePolyfill() {
  10473. }
  10474. /**
  10475. * Static function used to check if the polyfill is required
  10476. * If this is the case then the function will inject the polyfill to window.Promise
  10477. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10478. */
  10479. PromisePolyfill.Apply = function (force) {
  10480. if (force === void 0) { force = false; }
  10481. if (force || typeof Promise === 'undefined') {
  10482. var root = window;
  10483. root.Promise = InternalPromise;
  10484. }
  10485. };
  10486. return PromisePolyfill;
  10487. }());
  10488. BABYLON.PromisePolyfill = PromisePolyfill;
  10489. })(BABYLON || (BABYLON = {}));
  10490. //# sourceMappingURL=babylon.promise.js.map
  10491. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10492. var BABYLON;
  10493. (function (BABYLON) {
  10494. /**
  10495. * Helper class to push actions to a pool of workers.
  10496. */
  10497. var WorkerPool = /** @class */ (function () {
  10498. /**
  10499. * Constructor
  10500. * @param workers Array of workers to use for actions
  10501. */
  10502. function WorkerPool(workers) {
  10503. this._pendingActions = new Array();
  10504. this._workerInfos = workers.map(function (worker) { return ({
  10505. worker: worker,
  10506. active: false
  10507. }); });
  10508. }
  10509. /**
  10510. * Terminates all workers and clears any pending actions.
  10511. */
  10512. WorkerPool.prototype.dispose = function () {
  10513. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10514. var workerInfo = _a[_i];
  10515. workerInfo.worker.terminate();
  10516. }
  10517. delete this._workerInfos;
  10518. delete this._pendingActions;
  10519. };
  10520. /**
  10521. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10522. * pended until a worker has completed its action.
  10523. * @param action The action to perform. Call onComplete when the action is complete.
  10524. */
  10525. WorkerPool.prototype.push = function (action) {
  10526. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10527. var workerInfo = _a[_i];
  10528. if (!workerInfo.active) {
  10529. this._execute(workerInfo, action);
  10530. return;
  10531. }
  10532. }
  10533. this._pendingActions.push(action);
  10534. };
  10535. WorkerPool.prototype._execute = function (workerInfo, action) {
  10536. var _this = this;
  10537. workerInfo.active = true;
  10538. action(workerInfo.worker, function () {
  10539. workerInfo.active = false;
  10540. var nextAction = _this._pendingActions.shift();
  10541. if (nextAction) {
  10542. _this._execute(workerInfo, nextAction);
  10543. }
  10544. });
  10545. };
  10546. return WorkerPool;
  10547. }());
  10548. BABYLON.WorkerPool = WorkerPool;
  10549. })(BABYLON || (BABYLON = {}));
  10550. //# sourceMappingURL=babylon.workerPool.js.map
  10551. var BABYLON;
  10552. (function (BABYLON) {
  10553. /**
  10554. * @hidden
  10555. **/
  10556. var _AlphaState = /** @class */ (function () {
  10557. /**
  10558. * Initializes the state.
  10559. */
  10560. function _AlphaState() {
  10561. this._isAlphaBlendDirty = false;
  10562. this._isBlendFunctionParametersDirty = false;
  10563. this._isBlendEquationParametersDirty = false;
  10564. this._isBlendConstantsDirty = false;
  10565. this._alphaBlend = false;
  10566. this._blendFunctionParameters = new Array(4);
  10567. this._blendEquationParameters = new Array(2);
  10568. this._blendConstants = new Array(4);
  10569. this.reset();
  10570. }
  10571. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10572. get: function () {
  10573. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10574. },
  10575. enumerable: true,
  10576. configurable: true
  10577. });
  10578. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10579. get: function () {
  10580. return this._alphaBlend;
  10581. },
  10582. set: function (value) {
  10583. if (this._alphaBlend === value) {
  10584. return;
  10585. }
  10586. this._alphaBlend = value;
  10587. this._isAlphaBlendDirty = true;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10593. if (this._blendConstants[0] === r &&
  10594. this._blendConstants[1] === g &&
  10595. this._blendConstants[2] === b &&
  10596. this._blendConstants[3] === a) {
  10597. return;
  10598. }
  10599. this._blendConstants[0] = r;
  10600. this._blendConstants[1] = g;
  10601. this._blendConstants[2] = b;
  10602. this._blendConstants[3] = a;
  10603. this._isBlendConstantsDirty = true;
  10604. };
  10605. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10606. if (this._blendFunctionParameters[0] === value0 &&
  10607. this._blendFunctionParameters[1] === value1 &&
  10608. this._blendFunctionParameters[2] === value2 &&
  10609. this._blendFunctionParameters[3] === value3) {
  10610. return;
  10611. }
  10612. this._blendFunctionParameters[0] = value0;
  10613. this._blendFunctionParameters[1] = value1;
  10614. this._blendFunctionParameters[2] = value2;
  10615. this._blendFunctionParameters[3] = value3;
  10616. this._isBlendFunctionParametersDirty = true;
  10617. };
  10618. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10619. if (this._blendEquationParameters[0] === rgb &&
  10620. this._blendEquationParameters[1] === alpha) {
  10621. return;
  10622. }
  10623. this._blendEquationParameters[0] = rgb;
  10624. this._blendEquationParameters[1] = alpha;
  10625. this._isBlendEquationParametersDirty = true;
  10626. };
  10627. _AlphaState.prototype.reset = function () {
  10628. this._alphaBlend = false;
  10629. this._blendFunctionParameters[0] = null;
  10630. this._blendFunctionParameters[1] = null;
  10631. this._blendFunctionParameters[2] = null;
  10632. this._blendFunctionParameters[3] = null;
  10633. this._blendEquationParameters[0] = null;
  10634. this._blendEquationParameters[1] = null;
  10635. this._blendConstants[0] = null;
  10636. this._blendConstants[1] = null;
  10637. this._blendConstants[2] = null;
  10638. this._blendConstants[3] = null;
  10639. this._isAlphaBlendDirty = true;
  10640. this._isBlendFunctionParametersDirty = false;
  10641. this._isBlendEquationParametersDirty = false;
  10642. this._isBlendConstantsDirty = false;
  10643. };
  10644. _AlphaState.prototype.apply = function (gl) {
  10645. if (!this.isDirty) {
  10646. return;
  10647. }
  10648. // Alpha blend
  10649. if (this._isAlphaBlendDirty) {
  10650. if (this._alphaBlend) {
  10651. gl.enable(gl.BLEND);
  10652. }
  10653. else {
  10654. gl.disable(gl.BLEND);
  10655. }
  10656. this._isAlphaBlendDirty = false;
  10657. }
  10658. // Alpha function
  10659. if (this._isBlendFunctionParametersDirty) {
  10660. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10661. this._isBlendFunctionParametersDirty = false;
  10662. }
  10663. // Alpha equation
  10664. if (this._isBlendEquationParametersDirty) {
  10665. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10666. this._isBlendEquationParametersDirty = false;
  10667. }
  10668. // Constants
  10669. if (this._isBlendConstantsDirty) {
  10670. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10671. this._isBlendConstantsDirty = false;
  10672. }
  10673. };
  10674. return _AlphaState;
  10675. }());
  10676. BABYLON._AlphaState = _AlphaState;
  10677. })(BABYLON || (BABYLON = {}));
  10678. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10679. var BABYLON;
  10680. (function (BABYLON) {
  10681. /**
  10682. * @hidden
  10683. **/
  10684. var _DepthCullingState = /** @class */ (function () {
  10685. /**
  10686. * Initializes the state.
  10687. */
  10688. function _DepthCullingState() {
  10689. this._isDepthTestDirty = false;
  10690. this._isDepthMaskDirty = false;
  10691. this._isDepthFuncDirty = false;
  10692. this._isCullFaceDirty = false;
  10693. this._isCullDirty = false;
  10694. this._isZOffsetDirty = false;
  10695. this._isFrontFaceDirty = false;
  10696. this.reset();
  10697. }
  10698. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10699. get: function () {
  10700. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10706. get: function () {
  10707. return this._zOffset;
  10708. },
  10709. set: function (value) {
  10710. if (this._zOffset === value) {
  10711. return;
  10712. }
  10713. this._zOffset = value;
  10714. this._isZOffsetDirty = true;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10720. get: function () {
  10721. return this._cullFace;
  10722. },
  10723. set: function (value) {
  10724. if (this._cullFace === value) {
  10725. return;
  10726. }
  10727. this._cullFace = value;
  10728. this._isCullFaceDirty = true;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10734. get: function () {
  10735. return this._cull;
  10736. },
  10737. set: function (value) {
  10738. if (this._cull === value) {
  10739. return;
  10740. }
  10741. this._cull = value;
  10742. this._isCullDirty = true;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10748. get: function () {
  10749. return this._depthFunc;
  10750. },
  10751. set: function (value) {
  10752. if (this._depthFunc === value) {
  10753. return;
  10754. }
  10755. this._depthFunc = value;
  10756. this._isDepthFuncDirty = true;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10762. get: function () {
  10763. return this._depthMask;
  10764. },
  10765. set: function (value) {
  10766. if (this._depthMask === value) {
  10767. return;
  10768. }
  10769. this._depthMask = value;
  10770. this._isDepthMaskDirty = true;
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10776. get: function () {
  10777. return this._depthTest;
  10778. },
  10779. set: function (value) {
  10780. if (this._depthTest === value) {
  10781. return;
  10782. }
  10783. this._depthTest = value;
  10784. this._isDepthTestDirty = true;
  10785. },
  10786. enumerable: true,
  10787. configurable: true
  10788. });
  10789. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10790. get: function () {
  10791. return this._frontFace;
  10792. },
  10793. set: function (value) {
  10794. if (this._frontFace === value) {
  10795. return;
  10796. }
  10797. this._frontFace = value;
  10798. this._isFrontFaceDirty = true;
  10799. },
  10800. enumerable: true,
  10801. configurable: true
  10802. });
  10803. _DepthCullingState.prototype.reset = function () {
  10804. this._depthMask = true;
  10805. this._depthTest = true;
  10806. this._depthFunc = null;
  10807. this._cullFace = null;
  10808. this._cull = null;
  10809. this._zOffset = 0;
  10810. this._frontFace = null;
  10811. this._isDepthTestDirty = true;
  10812. this._isDepthMaskDirty = true;
  10813. this._isDepthFuncDirty = false;
  10814. this._isCullFaceDirty = false;
  10815. this._isCullDirty = false;
  10816. this._isZOffsetDirty = false;
  10817. this._isFrontFaceDirty = false;
  10818. };
  10819. _DepthCullingState.prototype.apply = function (gl) {
  10820. if (!this.isDirty) {
  10821. return;
  10822. }
  10823. // Cull
  10824. if (this._isCullDirty) {
  10825. if (this.cull) {
  10826. gl.enable(gl.CULL_FACE);
  10827. }
  10828. else {
  10829. gl.disable(gl.CULL_FACE);
  10830. }
  10831. this._isCullDirty = false;
  10832. }
  10833. // Cull face
  10834. if (this._isCullFaceDirty) {
  10835. gl.cullFace(this.cullFace);
  10836. this._isCullFaceDirty = false;
  10837. }
  10838. // Depth mask
  10839. if (this._isDepthMaskDirty) {
  10840. gl.depthMask(this.depthMask);
  10841. this._isDepthMaskDirty = false;
  10842. }
  10843. // Depth test
  10844. if (this._isDepthTestDirty) {
  10845. if (this.depthTest) {
  10846. gl.enable(gl.DEPTH_TEST);
  10847. }
  10848. else {
  10849. gl.disable(gl.DEPTH_TEST);
  10850. }
  10851. this._isDepthTestDirty = false;
  10852. }
  10853. // Depth func
  10854. if (this._isDepthFuncDirty) {
  10855. gl.depthFunc(this.depthFunc);
  10856. this._isDepthFuncDirty = false;
  10857. }
  10858. // zOffset
  10859. if (this._isZOffsetDirty) {
  10860. if (this.zOffset) {
  10861. gl.enable(gl.POLYGON_OFFSET_FILL);
  10862. gl.polygonOffset(this.zOffset, 0);
  10863. }
  10864. else {
  10865. gl.disable(gl.POLYGON_OFFSET_FILL);
  10866. }
  10867. this._isZOffsetDirty = false;
  10868. }
  10869. // Front face
  10870. if (this._isFrontFaceDirty) {
  10871. gl.frontFace(this.frontFace);
  10872. this._isFrontFaceDirty = false;
  10873. }
  10874. };
  10875. return _DepthCullingState;
  10876. }());
  10877. BABYLON._DepthCullingState = _DepthCullingState;
  10878. })(BABYLON || (BABYLON = {}));
  10879. //# sourceMappingURL=babylon.depthCullingState.js.map
  10880. var BABYLON;
  10881. (function (BABYLON) {
  10882. /**
  10883. * @hidden
  10884. **/
  10885. var _StencilState = /** @class */ (function () {
  10886. function _StencilState() {
  10887. this._isStencilTestDirty = false;
  10888. this._isStencilMaskDirty = false;
  10889. this._isStencilFuncDirty = false;
  10890. this._isStencilOpDirty = false;
  10891. this.reset();
  10892. }
  10893. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10894. get: function () {
  10895. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10901. get: function () {
  10902. return this._stencilFunc;
  10903. },
  10904. set: function (value) {
  10905. if (this._stencilFunc === value) {
  10906. return;
  10907. }
  10908. this._stencilFunc = value;
  10909. this._isStencilFuncDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10915. get: function () {
  10916. return this._stencilFuncRef;
  10917. },
  10918. set: function (value) {
  10919. if (this._stencilFuncRef === value) {
  10920. return;
  10921. }
  10922. this._stencilFuncRef = value;
  10923. this._isStencilFuncDirty = true;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10929. get: function () {
  10930. return this._stencilFuncMask;
  10931. },
  10932. set: function (value) {
  10933. if (this._stencilFuncMask === value) {
  10934. return;
  10935. }
  10936. this._stencilFuncMask = value;
  10937. this._isStencilFuncDirty = true;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10943. get: function () {
  10944. return this._stencilOpStencilFail;
  10945. },
  10946. set: function (value) {
  10947. if (this._stencilOpStencilFail === value) {
  10948. return;
  10949. }
  10950. this._stencilOpStencilFail = value;
  10951. this._isStencilOpDirty = true;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10957. get: function () {
  10958. return this._stencilOpDepthFail;
  10959. },
  10960. set: function (value) {
  10961. if (this._stencilOpDepthFail === value) {
  10962. return;
  10963. }
  10964. this._stencilOpDepthFail = value;
  10965. this._isStencilOpDirty = true;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10971. get: function () {
  10972. return this._stencilOpStencilDepthPass;
  10973. },
  10974. set: function (value) {
  10975. if (this._stencilOpStencilDepthPass === value) {
  10976. return;
  10977. }
  10978. this._stencilOpStencilDepthPass = value;
  10979. this._isStencilOpDirty = true;
  10980. },
  10981. enumerable: true,
  10982. configurable: true
  10983. });
  10984. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10985. get: function () {
  10986. return this._stencilMask;
  10987. },
  10988. set: function (value) {
  10989. if (this._stencilMask === value) {
  10990. return;
  10991. }
  10992. this._stencilMask = value;
  10993. this._isStencilMaskDirty = true;
  10994. },
  10995. enumerable: true,
  10996. configurable: true
  10997. });
  10998. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10999. get: function () {
  11000. return this._stencilTest;
  11001. },
  11002. set: function (value) {
  11003. if (this._stencilTest === value) {
  11004. return;
  11005. }
  11006. this._stencilTest = value;
  11007. this._isStencilTestDirty = true;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. _StencilState.prototype.reset = function () {
  11013. this._stencilTest = false;
  11014. this._stencilMask = 0xFF;
  11015. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11016. this._stencilFuncRef = 1;
  11017. this._stencilFuncMask = 0xFF;
  11018. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11019. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11020. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11021. this._isStencilTestDirty = true;
  11022. this._isStencilMaskDirty = true;
  11023. this._isStencilFuncDirty = true;
  11024. this._isStencilOpDirty = true;
  11025. };
  11026. _StencilState.prototype.apply = function (gl) {
  11027. if (!this.isDirty) {
  11028. return;
  11029. }
  11030. // Stencil test
  11031. if (this._isStencilTestDirty) {
  11032. if (this.stencilTest) {
  11033. gl.enable(gl.STENCIL_TEST);
  11034. }
  11035. else {
  11036. gl.disable(gl.STENCIL_TEST);
  11037. }
  11038. this._isStencilTestDirty = false;
  11039. }
  11040. // Stencil mask
  11041. if (this._isStencilMaskDirty) {
  11042. gl.stencilMask(this.stencilMask);
  11043. this._isStencilMaskDirty = false;
  11044. }
  11045. // Stencil func
  11046. if (this._isStencilFuncDirty) {
  11047. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11048. this._isStencilFuncDirty = false;
  11049. }
  11050. // Stencil op
  11051. if (this._isStencilOpDirty) {
  11052. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11053. this._isStencilOpDirty = false;
  11054. }
  11055. };
  11056. return _StencilState;
  11057. }());
  11058. BABYLON._StencilState = _StencilState;
  11059. })(BABYLON || (BABYLON = {}));
  11060. //# sourceMappingURL=babylon.stencilState.js.map
  11061. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11062. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11063. s = arguments[i];
  11064. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11065. t[p] = s[p];
  11066. }
  11067. return t;
  11068. };
  11069. var BABYLON;
  11070. (function (BABYLON) {
  11071. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11072. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11073. };
  11074. var compileRawShader = function (gl, source, type) {
  11075. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11076. gl.shaderSource(shader, source);
  11077. gl.compileShader(shader);
  11078. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11079. var log = gl.getShaderInfoLog(shader);
  11080. if (log) {
  11081. throw new Error(log);
  11082. }
  11083. }
  11084. if (!shader) {
  11085. throw new Error("Something went wrong while compile the shader.");
  11086. }
  11087. return shader;
  11088. };
  11089. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11090. var magFilter = gl.NEAREST;
  11091. var minFilter = gl.NEAREST;
  11092. switch (samplingMode) {
  11093. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11094. magFilter = gl.LINEAR;
  11095. if (generateMipMaps) {
  11096. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11097. }
  11098. else {
  11099. minFilter = gl.LINEAR;
  11100. }
  11101. break;
  11102. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11103. magFilter = gl.LINEAR;
  11104. if (generateMipMaps) {
  11105. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11106. }
  11107. else {
  11108. minFilter = gl.LINEAR;
  11109. }
  11110. break;
  11111. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11112. magFilter = gl.NEAREST;
  11113. if (generateMipMaps) {
  11114. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11115. }
  11116. else {
  11117. minFilter = gl.NEAREST;
  11118. }
  11119. break;
  11120. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11121. magFilter = gl.NEAREST;
  11122. if (generateMipMaps) {
  11123. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11124. }
  11125. else {
  11126. minFilter = gl.NEAREST;
  11127. }
  11128. break;
  11129. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11130. magFilter = gl.NEAREST;
  11131. if (generateMipMaps) {
  11132. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11133. }
  11134. else {
  11135. minFilter = gl.LINEAR;
  11136. }
  11137. break;
  11138. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11139. magFilter = gl.NEAREST;
  11140. if (generateMipMaps) {
  11141. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11142. }
  11143. else {
  11144. minFilter = gl.LINEAR;
  11145. }
  11146. break;
  11147. case BABYLON.Texture.NEAREST_LINEAR:
  11148. magFilter = gl.NEAREST;
  11149. minFilter = gl.LINEAR;
  11150. break;
  11151. case BABYLON.Texture.NEAREST_NEAREST:
  11152. magFilter = gl.NEAREST;
  11153. minFilter = gl.NEAREST;
  11154. break;
  11155. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11156. magFilter = gl.LINEAR;
  11157. if (generateMipMaps) {
  11158. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11159. }
  11160. else {
  11161. minFilter = gl.NEAREST;
  11162. }
  11163. break;
  11164. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11165. magFilter = gl.LINEAR;
  11166. if (generateMipMaps) {
  11167. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11168. }
  11169. else {
  11170. minFilter = gl.NEAREST;
  11171. }
  11172. break;
  11173. case BABYLON.Texture.LINEAR_LINEAR:
  11174. magFilter = gl.LINEAR;
  11175. minFilter = gl.LINEAR;
  11176. break;
  11177. case BABYLON.Texture.LINEAR_NEAREST:
  11178. magFilter = gl.LINEAR;
  11179. minFilter = gl.NEAREST;
  11180. break;
  11181. }
  11182. return {
  11183. min: minFilter,
  11184. mag: magFilter
  11185. };
  11186. };
  11187. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11188. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11189. var img;
  11190. var onload = function () {
  11191. loadedImages[index] = img;
  11192. loadedImages._internalCount++;
  11193. if (scene) {
  11194. scene._removePendingData(img);
  11195. }
  11196. if (loadedImages._internalCount === 6) {
  11197. onfinish(loadedImages);
  11198. }
  11199. };
  11200. var onerror = function (message, exception) {
  11201. if (scene) {
  11202. scene._removePendingData(img);
  11203. }
  11204. if (onErrorCallBack) {
  11205. onErrorCallBack(message, exception);
  11206. }
  11207. };
  11208. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11209. if (scene) {
  11210. scene._addPendingData(img);
  11211. }
  11212. };
  11213. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11214. if (onError === void 0) { onError = null; }
  11215. var loadedImages = [];
  11216. loadedImages._internalCount = 0;
  11217. for (var index = 0; index < 6; index++) {
  11218. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11219. }
  11220. };
  11221. var BufferPointer = /** @class */ (function () {
  11222. function BufferPointer() {
  11223. }
  11224. return BufferPointer;
  11225. }());
  11226. /**
  11227. * Interface for attribute information associated with buffer instanciation
  11228. */
  11229. var InstancingAttributeInfo = /** @class */ (function () {
  11230. function InstancingAttributeInfo() {
  11231. }
  11232. return InstancingAttributeInfo;
  11233. }());
  11234. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11235. /**
  11236. * Define options used to create a render target texture
  11237. */
  11238. var RenderTargetCreationOptions = /** @class */ (function () {
  11239. function RenderTargetCreationOptions() {
  11240. }
  11241. return RenderTargetCreationOptions;
  11242. }());
  11243. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11244. /**
  11245. * Define options used to create a depth texture
  11246. */
  11247. var DepthTextureCreationOptions = /** @class */ (function () {
  11248. function DepthTextureCreationOptions() {
  11249. }
  11250. return DepthTextureCreationOptions;
  11251. }());
  11252. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11253. /**
  11254. * Class used to describe the capabilities of the engine relatively to the current browser
  11255. */
  11256. var EngineCapabilities = /** @class */ (function () {
  11257. function EngineCapabilities() {
  11258. }
  11259. return EngineCapabilities;
  11260. }());
  11261. BABYLON.EngineCapabilities = EngineCapabilities;
  11262. /**
  11263. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11264. */
  11265. var Engine = /** @class */ (function () {
  11266. /**
  11267. * Creates a new engine
  11268. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11269. * @param antialias defines enable antialiasing (default: false)
  11270. * @param options defines further options to be sent to the getContext() function
  11271. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11272. */
  11273. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11274. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11275. var _this = this;
  11276. // Public members
  11277. /**
  11278. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11279. */
  11280. this.forcePOTTextures = false;
  11281. /**
  11282. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11283. */
  11284. this.isFullscreen = false;
  11285. /**
  11286. * Gets a boolean indicating if the pointer is currently locked
  11287. */
  11288. this.isPointerLock = false;
  11289. /**
  11290. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11291. */
  11292. this.cullBackFaces = true;
  11293. /**
  11294. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11295. */
  11296. this.renderEvenInBackground = true;
  11297. /**
  11298. * Gets or sets a boolean indicating that cache can be kept between frames
  11299. */
  11300. this.preventCacheWipeBetweenFrames = false;
  11301. /**
  11302. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11303. **/
  11304. this.enableOfflineSupport = false;
  11305. /**
  11306. * 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)
  11307. **/
  11308. this.disableManifestCheck = false;
  11309. /**
  11310. * Gets the list of created scenes
  11311. */
  11312. this.scenes = new Array();
  11313. /**
  11314. * Gets the list of created postprocesses
  11315. */
  11316. this.postProcesses = new Array();
  11317. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11318. this.validateShaderPrograms = false;
  11319. // Observables
  11320. /**
  11321. * Observable event triggered each time the rendering canvas is resized
  11322. */
  11323. this.onResizeObservable = new BABYLON.Observable();
  11324. /**
  11325. * Observable event triggered each time the canvas loses focus
  11326. */
  11327. this.onCanvasBlurObservable = new BABYLON.Observable();
  11328. /**
  11329. * Observable event triggered each time the canvas gains focus
  11330. */
  11331. this.onCanvasFocusObservable = new BABYLON.Observable();
  11332. /**
  11333. * Observable event triggered each time the canvas receives pointerout event
  11334. */
  11335. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11336. /**
  11337. * Observable event triggered before each texture is initialized
  11338. */
  11339. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11340. //WebVR
  11341. this._vrDisplay = undefined;
  11342. this._vrSupported = false;
  11343. this._vrExclusivePointerMode = false;
  11344. // Uniform buffers list
  11345. /**
  11346. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11347. */
  11348. this.disableUniformBuffers = false;
  11349. /** @hidden */
  11350. this._uniformBuffers = new Array();
  11351. // Observables
  11352. /**
  11353. * Observable raised when the engine begins a new frame
  11354. */
  11355. this.onBeginFrameObservable = new BABYLON.Observable();
  11356. /**
  11357. * Observable raised when the engine ends the current frame
  11358. */
  11359. this.onEndFrameObservable = new BABYLON.Observable();
  11360. /**
  11361. * Observable raised when the engine is about to compile a shader
  11362. */
  11363. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11364. /**
  11365. * Observable raised when the engine has jsut compiled a shader
  11366. */
  11367. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11368. this._windowIsBackground = false;
  11369. this._webGLVersion = 1.0;
  11370. /** @hidden */
  11371. this._badOS = false;
  11372. /** @hidden */
  11373. this._badDesktopOS = false;
  11374. /**
  11375. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11376. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11377. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11378. */
  11379. this.disableTextureBindingOptimization = false;
  11380. /**
  11381. * Observable signaled when VR display mode changes
  11382. */
  11383. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable signaled when VR request present is complete
  11386. */
  11387. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11388. /**
  11389. * Observable signaled when VR request present starts
  11390. */
  11391. this.onVRRequestPresentStart = new BABYLON.Observable();
  11392. this._colorWrite = true;
  11393. /** @hidden */
  11394. this._drawCalls = new BABYLON.PerfCounter();
  11395. /** @hidden */
  11396. this._textureCollisions = new BABYLON.PerfCounter();
  11397. this._renderingQueueLaunched = false;
  11398. this._activeRenderLoops = new Array();
  11399. // Deterministic lockstepMaxSteps
  11400. this._deterministicLockstep = false;
  11401. this._lockstepMaxSteps = 4;
  11402. // Lost context
  11403. /**
  11404. * Observable signaled when a context lost event is raised
  11405. */
  11406. this.onContextLostObservable = new BABYLON.Observable();
  11407. /**
  11408. * Observable signaled when a context restored event is raised
  11409. */
  11410. this.onContextRestoredObservable = new BABYLON.Observable();
  11411. this._contextWasLost = false;
  11412. this._doNotHandleContextLost = false;
  11413. // FPS
  11414. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11415. this._fps = 60;
  11416. this._deltaTime = 0;
  11417. /**
  11418. * Turn this value on if you want to pause FPS computation when in background
  11419. */
  11420. this.disablePerformanceMonitorInBackground = false;
  11421. // States
  11422. /** @hidden */
  11423. this._depthCullingState = new BABYLON._DepthCullingState();
  11424. /** @hidden */
  11425. this._stencilState = new BABYLON._StencilState();
  11426. /** @hidden */
  11427. this._alphaState = new BABYLON._AlphaState();
  11428. /** @hidden */
  11429. this._alphaMode = Engine.ALPHA_DISABLE;
  11430. // Cache
  11431. this._internalTexturesCache = new Array();
  11432. /** @hidden */
  11433. this._activeChannel = 0;
  11434. this._currentTextureChannel = -1;
  11435. /** @hidden */
  11436. this._boundTexturesCache = {};
  11437. this._compiledEffects = {};
  11438. this._vertexAttribArraysEnabled = [];
  11439. this._uintIndicesCurrentlySet = false;
  11440. this._currentBoundBuffer = new Array();
  11441. /** @hidden */
  11442. this._currentFramebuffer = null;
  11443. this._currentBufferPointers = new Array();
  11444. this._currentInstanceLocations = new Array();
  11445. this._currentInstanceBuffers = new Array();
  11446. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11447. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11448. this._vaoRecordInProgress = false;
  11449. this._mustWipeVertexAttributes = false;
  11450. this._nextFreeTextureSlots = new Array();
  11451. this._maxSimultaneousTextures = 0;
  11452. this._activeRequests = new Array();
  11453. // Hardware supported Compressed Textures
  11454. this._texturesSupported = new Array();
  11455. /**
  11456. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11457. */
  11458. this.premultipliedAlpha = true;
  11459. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11460. this._onVRFullScreenTriggered = function () {
  11461. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11462. //get the old size before we change
  11463. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11464. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11465. //get the width and height, change the render size
  11466. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11467. _this.setHardwareScalingLevel(1);
  11468. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11469. }
  11470. else {
  11471. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11472. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11473. }
  11474. };
  11475. this._unpackFlipYCached = null;
  11476. this._boundUniforms = {};
  11477. // Register promises
  11478. BABYLON.PromisePolyfill.Apply();
  11479. var canvas = null;
  11480. Engine.Instances.push(this);
  11481. if (!canvasOrContext) {
  11482. return;
  11483. }
  11484. options = options || {};
  11485. if (canvasOrContext.getContext) {
  11486. canvas = canvasOrContext;
  11487. this._renderingCanvas = canvas;
  11488. if (antialias != null) {
  11489. options.antialias = antialias;
  11490. }
  11491. if (options.deterministicLockstep === undefined) {
  11492. options.deterministicLockstep = false;
  11493. }
  11494. if (options.lockstepMaxSteps === undefined) {
  11495. options.lockstepMaxSteps = 4;
  11496. }
  11497. if (options.preserveDrawingBuffer === undefined) {
  11498. options.preserveDrawingBuffer = false;
  11499. }
  11500. if (options.audioEngine === undefined) {
  11501. options.audioEngine = true;
  11502. }
  11503. if (options.stencil === undefined) {
  11504. options.stencil = true;
  11505. }
  11506. if (options.premultipliedAlpha === false) {
  11507. this.premultipliedAlpha = false;
  11508. }
  11509. this._deterministicLockstep = options.deterministicLockstep;
  11510. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11511. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11512. // Exceptions
  11513. if (navigator && navigator.userAgent) {
  11514. var ua = navigator.userAgent;
  11515. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11516. var exception = _a[_i];
  11517. var key = exception.key;
  11518. var targets = exception.targets;
  11519. if (ua.indexOf(key) > -1) {
  11520. if (exception.capture && exception.captureConstraint) {
  11521. var capture = exception.capture;
  11522. var constraint = exception.captureConstraint;
  11523. var regex = new RegExp(capture);
  11524. var matches = regex.exec(ua);
  11525. if (matches && matches.length > 0) {
  11526. var capturedValue = parseInt(matches[matches.length - 1]);
  11527. if (capturedValue >= constraint) {
  11528. continue;
  11529. }
  11530. }
  11531. }
  11532. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11533. var target = targets_1[_b];
  11534. switch (target) {
  11535. case "uniformBuffer":
  11536. this.disableUniformBuffers = true;
  11537. break;
  11538. case "textureBindingOptimization":
  11539. this.disableTextureBindingOptimization = true;
  11540. break;
  11541. }
  11542. }
  11543. }
  11544. }
  11545. }
  11546. // GL
  11547. if (!options.disableWebGL2Support) {
  11548. try {
  11549. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11550. if (this._gl) {
  11551. this._webGLVersion = 2.0;
  11552. }
  11553. }
  11554. catch (e) {
  11555. // Do nothing
  11556. }
  11557. }
  11558. if (!this._gl) {
  11559. if (!canvas) {
  11560. throw new Error("The provided canvas is null or undefined.");
  11561. }
  11562. try {
  11563. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11564. }
  11565. catch (e) {
  11566. throw new Error("WebGL not supported");
  11567. }
  11568. }
  11569. if (!this._gl) {
  11570. throw new Error("WebGL not supported");
  11571. }
  11572. this._onCanvasFocus = function () {
  11573. _this.onCanvasFocusObservable.notifyObservers(_this);
  11574. };
  11575. this._onCanvasBlur = function () {
  11576. _this.onCanvasBlurObservable.notifyObservers(_this);
  11577. };
  11578. canvas.addEventListener("focus", this._onCanvasFocus);
  11579. canvas.addEventListener("blur", this._onCanvasBlur);
  11580. this._onBlur = function () {
  11581. if (_this.disablePerformanceMonitorInBackground) {
  11582. _this._performanceMonitor.disable();
  11583. }
  11584. _this._windowIsBackground = true;
  11585. };
  11586. this._onFocus = function () {
  11587. if (_this.disablePerformanceMonitorInBackground) {
  11588. _this._performanceMonitor.enable();
  11589. }
  11590. _this._windowIsBackground = false;
  11591. };
  11592. this._onCanvasPointerOut = function (ev) {
  11593. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11594. };
  11595. window.addEventListener("blur", this._onBlur);
  11596. window.addEventListener("focus", this._onFocus);
  11597. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11598. // Context lost
  11599. if (!this._doNotHandleContextLost) {
  11600. this._onContextLost = function (evt) {
  11601. evt.preventDefault();
  11602. _this._contextWasLost = true;
  11603. BABYLON.Tools.Warn("WebGL context lost.");
  11604. _this.onContextLostObservable.notifyObservers(_this);
  11605. };
  11606. this._onContextRestored = function (evt) {
  11607. // Adding a timeout to avoid race condition at browser level
  11608. setTimeout(function () {
  11609. // Rebuild gl context
  11610. _this._initGLContext();
  11611. // Rebuild effects
  11612. _this._rebuildEffects();
  11613. // Rebuild textures
  11614. _this._rebuildInternalTextures();
  11615. // Rebuild buffers
  11616. _this._rebuildBuffers();
  11617. // Cache
  11618. _this.wipeCaches(true);
  11619. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11620. _this.onContextRestoredObservable.notifyObservers(_this);
  11621. _this._contextWasLost = false;
  11622. }, 0);
  11623. };
  11624. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11625. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11626. }
  11627. }
  11628. else {
  11629. this._gl = canvasOrContext;
  11630. this._renderingCanvas = this._gl.canvas;
  11631. if (this._gl.renderbufferStorageMultisample) {
  11632. this._webGLVersion = 2.0;
  11633. }
  11634. options.stencil = this._gl.getContextAttributes().stencil;
  11635. }
  11636. // Viewport
  11637. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11638. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11639. this.resize();
  11640. this._isStencilEnable = options.stencil ? true : false;
  11641. this._initGLContext();
  11642. if (canvas) {
  11643. // Fullscreen
  11644. this._onFullscreenChange = function () {
  11645. if (document.fullscreen !== undefined) {
  11646. _this.isFullscreen = document.fullscreen;
  11647. }
  11648. else if (document.mozFullScreen !== undefined) {
  11649. _this.isFullscreen = document.mozFullScreen;
  11650. }
  11651. else if (document.webkitIsFullScreen !== undefined) {
  11652. _this.isFullscreen = document.webkitIsFullScreen;
  11653. }
  11654. else if (document.msIsFullScreen !== undefined) {
  11655. _this.isFullscreen = document.msIsFullScreen;
  11656. }
  11657. // Pointer lock
  11658. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11659. canvas.requestPointerLock = canvas.requestPointerLock ||
  11660. canvas.msRequestPointerLock ||
  11661. canvas.mozRequestPointerLock ||
  11662. canvas.webkitRequestPointerLock;
  11663. if (canvas.requestPointerLock) {
  11664. canvas.requestPointerLock();
  11665. }
  11666. }
  11667. };
  11668. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11669. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11670. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11671. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11672. // Pointer lock
  11673. this._onPointerLockChange = function () {
  11674. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11675. document.webkitPointerLockElement === canvas ||
  11676. document.msPointerLockElement === canvas ||
  11677. document.pointerLockElement === canvas);
  11678. };
  11679. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11680. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11681. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11682. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11683. this._onVRDisplayPointerRestricted = function () {
  11684. if (canvas) {
  11685. canvas.requestPointerLock();
  11686. }
  11687. };
  11688. this._onVRDisplayPointerUnrestricted = function () {
  11689. document.exitPointerLock();
  11690. };
  11691. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11692. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11693. }
  11694. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11695. Engine.audioEngine = new BABYLON.AudioEngine();
  11696. }
  11697. // Prepare buffer pointers
  11698. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11699. this._currentBufferPointers[i] = new BufferPointer();
  11700. }
  11701. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11702. // Load WebVR Devices
  11703. if (options.autoEnableWebVR) {
  11704. this.initWebVR();
  11705. }
  11706. // Detect if we are running on a faulty buggy OS.
  11707. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11708. // Detect if we are running on a faulty buggy desktop OS.
  11709. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11710. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11711. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11712. }
  11713. Object.defineProperty(Engine, "LastCreatedEngine", {
  11714. /**
  11715. * Gets the latest created engine
  11716. */
  11717. get: function () {
  11718. if (Engine.Instances.length === 0) {
  11719. return null;
  11720. }
  11721. return Engine.Instances[Engine.Instances.length - 1];
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Engine, "LastCreatedScene", {
  11727. /**
  11728. * Gets the latest created scene
  11729. */
  11730. get: function () {
  11731. var lastCreatedEngine = Engine.LastCreatedEngine;
  11732. if (!lastCreatedEngine) {
  11733. return null;
  11734. }
  11735. if (lastCreatedEngine.scenes.length === 0) {
  11736. return null;
  11737. }
  11738. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. /**
  11744. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11745. * @param flag defines which part of the materials must be marked as dirty
  11746. * @param predicate defines a predicate used to filter which materials should be affected
  11747. */
  11748. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11749. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11750. var engine = Engine.Instances[engineIndex];
  11751. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11752. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11753. }
  11754. }
  11755. };
  11756. Object.defineProperty(Engine, "NEVER", {
  11757. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11758. get: function () {
  11759. return Engine._NEVER;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine, "ALWAYS", {
  11765. /** 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 */
  11766. get: function () {
  11767. return Engine._ALWAYS;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine, "LESS", {
  11773. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11774. get: function () {
  11775. return Engine._LESS;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine, "EQUAL", {
  11781. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11782. get: function () {
  11783. return Engine._EQUAL;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "LEQUAL", {
  11789. /** 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 */
  11790. get: function () {
  11791. return Engine._LEQUAL;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "GREATER", {
  11797. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11798. get: function () {
  11799. return Engine._GREATER;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "GEQUAL", {
  11805. /** 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 */
  11806. get: function () {
  11807. return Engine._GEQUAL;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "NOTEQUAL", {
  11813. /** 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 */
  11814. get: function () {
  11815. return Engine._NOTEQUAL;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "KEEP", {
  11821. /** Passed to stencilOperation to specify that stencil value must be kept */
  11822. get: function () {
  11823. return Engine._KEEP;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "REPLACE", {
  11829. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11830. get: function () {
  11831. return Engine._REPLACE;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(Engine, "INCR", {
  11837. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11838. get: function () {
  11839. return Engine._INCR;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine, "DECR", {
  11845. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11846. get: function () {
  11847. return Engine._DECR;
  11848. },
  11849. enumerable: true,
  11850. configurable: true
  11851. });
  11852. Object.defineProperty(Engine, "INVERT", {
  11853. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11854. get: function () {
  11855. return Engine._INVERT;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine, "INCR_WRAP", {
  11861. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11862. get: function () {
  11863. return Engine._INCR_WRAP;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Engine, "DECR_WRAP", {
  11869. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11870. get: function () {
  11871. return Engine._DECR_WRAP;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11877. // Alpha
  11878. /** Defines that alpha blending is disabled */
  11879. get: function () {
  11880. return Engine._ALPHA_DISABLE;
  11881. },
  11882. enumerable: true,
  11883. configurable: true
  11884. });
  11885. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11886. /** Defines that alpha blending to SRC + DEST */
  11887. get: function () {
  11888. return Engine._ALPHA_ONEONE;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(Engine, "ALPHA_ADD", {
  11894. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11895. get: function () {
  11896. return Engine._ALPHA_ADD;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11902. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11903. get: function () {
  11904. return Engine._ALPHA_COMBINE;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11910. /** Defines that alpha blending to DEST - SRC * DEST */
  11911. get: function () {
  11912. return Engine._ALPHA_SUBTRACT;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11918. /** Defines that alpha blending to SRC * DEST */
  11919. get: function () {
  11920. return Engine._ALPHA_MULTIPLY;
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11926. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11927. get: function () {
  11928. return Engine._ALPHA_MAXIMIZED;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11934. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11935. get: function () {
  11936. return Engine._ALPHA_PREMULTIPLIED;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11942. /**
  11943. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11944. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11945. */
  11946. get: function () {
  11947. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11953. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11954. get: function () {
  11955. return Engine._ALPHA_INTERPOLATE;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11961. /**
  11962. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11963. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11964. */
  11965. get: function () {
  11966. return Engine._ALPHA_SCREENMODE;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11972. // Delays
  11973. /** Defines that the ressource is not delayed*/
  11974. get: function () {
  11975. return Engine._DELAYLOADSTATE_NONE;
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11981. /** Defines that the ressource was successfully delay loaded */
  11982. get: function () {
  11983. return Engine._DELAYLOADSTATE_LOADED;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11989. /** Defines that the ressource is currently delay loading */
  11990. get: function () {
  11991. return Engine._DELAYLOADSTATE_LOADING;
  11992. },
  11993. enumerable: true,
  11994. configurable: true
  11995. });
  11996. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11997. /** Defines that the ressource is delayed and has not started loading */
  11998. get: function () {
  11999. return Engine._DELAYLOADSTATE_NOTLOADED;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12005. /** ALPHA */
  12006. get: function () {
  12007. return Engine._TEXTUREFORMAT_ALPHA;
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12013. /** LUMINANCE */
  12014. get: function () {
  12015. return Engine._TEXTUREFORMAT_LUMINANCE;
  12016. },
  12017. enumerable: true,
  12018. configurable: true
  12019. });
  12020. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12021. /**
  12022. * R
  12023. */
  12024. get: function () {
  12025. return Engine._TEXTUREFORMAT_R;
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12031. /**
  12032. * RG
  12033. */
  12034. get: function () {
  12035. return Engine._TEXTUREFORMAT_RG;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12041. /** LUMINANCE_ALPHA */
  12042. get: function () {
  12043. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12049. /** RGB */
  12050. get: function () {
  12051. return Engine._TEXTUREFORMAT_RGB;
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12057. /** RGBA */
  12058. get: function () {
  12059. return Engine._TEXTUREFORMAT_RGBA;
  12060. },
  12061. enumerable: true,
  12062. configurable: true
  12063. });
  12064. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12065. /** UNSIGNED_INT */
  12066. get: function () {
  12067. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12073. /** FLOAT */
  12074. get: function () {
  12075. return Engine._TEXTURETYPE_FLOAT;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12081. /** HALF_FLOAT */
  12082. get: function () {
  12083. return Engine._TEXTURETYPE_HALF_FLOAT;
  12084. },
  12085. enumerable: true,
  12086. configurable: true
  12087. });
  12088. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12089. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12090. get: function () {
  12091. return Engine._SCALEMODE_FLOOR;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12097. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12098. get: function () {
  12099. return Engine._SCALEMODE_NEAREST;
  12100. },
  12101. enumerable: true,
  12102. configurable: true
  12103. });
  12104. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12105. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12106. get: function () {
  12107. return Engine._SCALEMODE_CEILING;
  12108. },
  12109. enumerable: true,
  12110. configurable: true
  12111. });
  12112. Object.defineProperty(Engine, "Version", {
  12113. /**
  12114. * Returns the current version of the framework
  12115. */
  12116. get: function () {
  12117. return "3.3.0-alpha.9";
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12123. /**
  12124. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12125. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12126. */
  12127. get: function () {
  12128. return this._vrExclusivePointerMode;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12134. /**
  12135. * Gets a boolean indicating that the engine supports uniform buffers
  12136. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12137. */
  12138. get: function () {
  12139. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12140. },
  12141. enumerable: true,
  12142. configurable: true
  12143. });
  12144. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12145. /**
  12146. * Gets a boolean indicating that only power of 2 textures are supported
  12147. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12148. */
  12149. get: function () {
  12150. return this._webGLVersion < 2 || this.forcePOTTextures;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12156. /**
  12157. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12158. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12159. */
  12160. get: function () {
  12161. return this._doNotHandleContextLost;
  12162. },
  12163. set: function (value) {
  12164. this._doNotHandleContextLost = value;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12170. /**
  12171. * Gets the performance monitor attached to this engine
  12172. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12173. */
  12174. get: function () {
  12175. return this._performanceMonitor;
  12176. },
  12177. enumerable: true,
  12178. configurable: true
  12179. });
  12180. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12181. /**
  12182. * Gets the list of texture formats supported
  12183. */
  12184. get: function () {
  12185. return this._texturesSupported;
  12186. },
  12187. enumerable: true,
  12188. configurable: true
  12189. });
  12190. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12191. /**
  12192. * Gets the list of texture formats in use
  12193. */
  12194. get: function () {
  12195. return this._textureFormatInUse;
  12196. },
  12197. enumerable: true,
  12198. configurable: true
  12199. });
  12200. Object.defineProperty(Engine.prototype, "currentViewport", {
  12201. /**
  12202. * Gets the current viewport
  12203. */
  12204. get: function () {
  12205. return this._cachedViewport;
  12206. },
  12207. enumerable: true,
  12208. configurable: true
  12209. });
  12210. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12211. /**
  12212. * Gets the default empty texture
  12213. */
  12214. get: function () {
  12215. if (!this._emptyTexture) {
  12216. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12217. }
  12218. return this._emptyTexture;
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12224. /**
  12225. * Gets the default empty 3D texture
  12226. */
  12227. get: function () {
  12228. if (!this._emptyTexture3D) {
  12229. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12230. }
  12231. return this._emptyTexture3D;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12237. /**
  12238. * Gets the default empty cube texture
  12239. */
  12240. get: function () {
  12241. if (!this._emptyCubeTexture) {
  12242. var faceData = new Uint8Array(4);
  12243. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12244. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12245. }
  12246. return this._emptyCubeTexture;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Engine.prototype._rebuildInternalTextures = function () {
  12252. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12253. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12254. var internalTexture = currentState_1[_i];
  12255. internalTexture._rebuild();
  12256. }
  12257. };
  12258. Engine.prototype._rebuildEffects = function () {
  12259. for (var key in this._compiledEffects) {
  12260. var effect = this._compiledEffects[key];
  12261. effect._prepareEffect();
  12262. }
  12263. BABYLON.Effect.ResetCache();
  12264. };
  12265. Engine.prototype._rebuildBuffers = function () {
  12266. // Index / Vertex
  12267. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12268. var scene = _a[_i];
  12269. scene.resetCachedMaterial();
  12270. scene._rebuildGeometries();
  12271. scene._rebuildTextures();
  12272. }
  12273. // Uniforms
  12274. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12275. var uniformBuffer = _c[_b];
  12276. uniformBuffer._rebuild();
  12277. }
  12278. };
  12279. Engine.prototype._initGLContext = function () {
  12280. // Caps
  12281. this._caps = new EngineCapabilities();
  12282. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12283. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12284. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12285. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12286. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12287. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12288. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12289. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12290. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12291. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12292. // Infos
  12293. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12294. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12295. if (rendererInfo != null) {
  12296. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12297. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12298. }
  12299. if (!this._glVendor) {
  12300. this._glVendor = "Unknown vendor";
  12301. }
  12302. if (!this._glRenderer) {
  12303. this._glRenderer = "Unknown renderer";
  12304. }
  12305. // Constants
  12306. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12307. if (this._gl.RGBA16F !== 0x881A) {
  12308. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12309. }
  12310. if (this._gl.RGBA32F !== 0x8814) {
  12311. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12312. }
  12313. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12314. this._gl.DEPTH24_STENCIL8 = 35056;
  12315. }
  12316. // Extensions
  12317. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12318. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12319. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12320. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12321. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12322. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12323. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12324. 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');
  12325. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12326. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12327. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12328. this._caps.highPrecisionShaderSupported = true;
  12329. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12330. if (this._caps.timerQuery) {
  12331. if (this._webGLVersion === 1) {
  12332. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12333. }
  12334. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12335. }
  12336. // Checks if some of the format renders first to allow the use of webgl inspector.
  12337. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12338. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12339. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12340. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12341. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12342. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12343. if (this._webGLVersion > 1) {
  12344. this._gl.HALF_FLOAT_OES = 0x140B;
  12345. }
  12346. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12347. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12348. // Draw buffers
  12349. if (this._webGLVersion > 1) {
  12350. this._caps.drawBuffersExtension = true;
  12351. }
  12352. else {
  12353. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12354. if (drawBuffersExtension !== null) {
  12355. this._caps.drawBuffersExtension = true;
  12356. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12357. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12358. for (var i = 0; i < 16; i++) {
  12359. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12360. }
  12361. }
  12362. else {
  12363. this._caps.drawBuffersExtension = false;
  12364. }
  12365. }
  12366. // Depth Texture
  12367. if (this._webGLVersion > 1) {
  12368. this._caps.depthTextureExtension = true;
  12369. }
  12370. else {
  12371. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12372. if (depthTextureExtension != null) {
  12373. this._caps.depthTextureExtension = true;
  12374. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12375. }
  12376. }
  12377. // Vertex array object
  12378. if (this._webGLVersion > 1) {
  12379. this._caps.vertexArrayObject = true;
  12380. }
  12381. else {
  12382. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12383. if (vertexArrayObjectExtension != null) {
  12384. this._caps.vertexArrayObject = true;
  12385. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12386. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12387. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12388. }
  12389. else {
  12390. this._caps.vertexArrayObject = false;
  12391. }
  12392. }
  12393. // Instances count
  12394. if (this._webGLVersion > 1) {
  12395. this._caps.instancedArrays = true;
  12396. }
  12397. else {
  12398. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12399. if (instanceExtension != null) {
  12400. this._caps.instancedArrays = true;
  12401. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12402. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12403. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12404. }
  12405. else {
  12406. this._caps.instancedArrays = false;
  12407. }
  12408. }
  12409. // Intelligently add supported compressed formats in order to check for.
  12410. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12411. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12412. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12413. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12414. if (this._caps.astc)
  12415. this.texturesSupported.push('-astc.ktx');
  12416. if (this._caps.s3tc)
  12417. this.texturesSupported.push('-dxt.ktx');
  12418. if (this._caps.pvrtc)
  12419. this.texturesSupported.push('-pvrtc.ktx');
  12420. if (this._caps.etc2)
  12421. this.texturesSupported.push('-etc2.ktx');
  12422. if (this._caps.etc1)
  12423. this.texturesSupported.push('-etc1.ktx');
  12424. if (this._gl.getShaderPrecisionFormat) {
  12425. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12426. if (highp) {
  12427. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12428. }
  12429. }
  12430. // Depth buffer
  12431. this.setDepthBuffer(true);
  12432. this.setDepthFunctionToLessOrEqual();
  12433. this.setDepthWrite(true);
  12434. // Texture maps
  12435. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12436. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12437. this._nextFreeTextureSlots.push(slot);
  12438. }
  12439. };
  12440. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12441. /**
  12442. * Gets version of the current webGL context
  12443. */
  12444. get: function () {
  12445. return this._webGLVersion;
  12446. },
  12447. enumerable: true,
  12448. configurable: true
  12449. });
  12450. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12451. /**
  12452. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12453. */
  12454. get: function () {
  12455. return this._isStencilEnable;
  12456. },
  12457. enumerable: true,
  12458. configurable: true
  12459. });
  12460. Engine.prototype._prepareWorkingCanvas = function () {
  12461. if (this._workingCanvas) {
  12462. return;
  12463. }
  12464. this._workingCanvas = document.createElement("canvas");
  12465. var context = this._workingCanvas.getContext("2d");
  12466. if (context) {
  12467. this._workingContext = context;
  12468. }
  12469. };
  12470. /**
  12471. * Reset the texture cache to empty state
  12472. */
  12473. Engine.prototype.resetTextureCache = function () {
  12474. for (var key in this._boundTexturesCache) {
  12475. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12476. continue;
  12477. }
  12478. var boundTexture = this._boundTexturesCache[key];
  12479. if (boundTexture) {
  12480. this._removeDesignatedSlot(boundTexture);
  12481. }
  12482. this._boundTexturesCache[key] = null;
  12483. }
  12484. if (!this.disableTextureBindingOptimization) {
  12485. this._nextFreeTextureSlots = [];
  12486. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12487. this._nextFreeTextureSlots.push(slot);
  12488. }
  12489. }
  12490. this._currentTextureChannel = -1;
  12491. };
  12492. /**
  12493. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12494. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12495. * @returns true if engine is in deterministic lock step mode
  12496. */
  12497. Engine.prototype.isDeterministicLockStep = function () {
  12498. return this._deterministicLockstep;
  12499. };
  12500. /**
  12501. * Gets the max steps when engine is running in deterministic lock step
  12502. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12503. * @returns the max steps
  12504. */
  12505. Engine.prototype.getLockstepMaxSteps = function () {
  12506. return this._lockstepMaxSteps;
  12507. };
  12508. /**
  12509. * Gets an object containing information about the current webGL context
  12510. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12511. */
  12512. Engine.prototype.getGlInfo = function () {
  12513. return {
  12514. vendor: this._glVendor,
  12515. renderer: this._glRenderer,
  12516. version: this._glVersion
  12517. };
  12518. };
  12519. /**
  12520. * Gets current aspect ratio
  12521. * @param camera defines the camera to use to get the aspect ratio
  12522. * @param useScreen defines if screen size must be used (or the current render target if any)
  12523. * @returns a number defining the aspect ratio
  12524. */
  12525. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12526. if (useScreen === void 0) { useScreen = false; }
  12527. var viewport = camera.viewport;
  12528. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12529. };
  12530. /**
  12531. * Gets current screen aspect ratio
  12532. * @returns a number defining the aspect ratio
  12533. */
  12534. Engine.prototype.getScreenAspectRatio = function () {
  12535. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12536. };
  12537. /**
  12538. * Gets the current render width
  12539. * @param useScreen defines if screen size must be used (or the current render target if any)
  12540. * @returns a number defining the current render width
  12541. */
  12542. Engine.prototype.getRenderWidth = function (useScreen) {
  12543. if (useScreen === void 0) { useScreen = false; }
  12544. if (!useScreen && this._currentRenderTarget) {
  12545. return this._currentRenderTarget.width;
  12546. }
  12547. return this._gl.drawingBufferWidth;
  12548. };
  12549. /**
  12550. * Gets the current render height
  12551. * @param useScreen defines if screen size must be used (or the current render target if any)
  12552. * @returns a number defining the current render height
  12553. */
  12554. Engine.prototype.getRenderHeight = function (useScreen) {
  12555. if (useScreen === void 0) { useScreen = false; }
  12556. if (!useScreen && this._currentRenderTarget) {
  12557. return this._currentRenderTarget.height;
  12558. }
  12559. return this._gl.drawingBufferHeight;
  12560. };
  12561. /**
  12562. * Gets the HTML canvas attached with the current webGL context
  12563. * @returns a HTML canvas
  12564. */
  12565. Engine.prototype.getRenderingCanvas = function () {
  12566. return this._renderingCanvas;
  12567. };
  12568. /**
  12569. * Gets the client rect of the HTML canvas attached with the current webGL context
  12570. * @returns a client rectanglee
  12571. */
  12572. Engine.prototype.getRenderingCanvasClientRect = function () {
  12573. if (!this._renderingCanvas) {
  12574. return null;
  12575. }
  12576. return this._renderingCanvas.getBoundingClientRect();
  12577. };
  12578. /**
  12579. * Defines the hardware scaling level.
  12580. * By default the hardware scaling level is computed from the window device ratio.
  12581. * 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.
  12582. * @param level defines the level to use
  12583. */
  12584. Engine.prototype.setHardwareScalingLevel = function (level) {
  12585. this._hardwareScalingLevel = level;
  12586. this.resize();
  12587. };
  12588. /**
  12589. * Gets the current hardware scaling level.
  12590. * By default the hardware scaling level is computed from the window device ratio.
  12591. * 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.
  12592. * @returns a number indicating the current hardware scaling level
  12593. */
  12594. Engine.prototype.getHardwareScalingLevel = function () {
  12595. return this._hardwareScalingLevel;
  12596. };
  12597. /**
  12598. * Gets the list of loaded textures
  12599. * @returns an array containing all loaded textures
  12600. */
  12601. Engine.prototype.getLoadedTexturesCache = function () {
  12602. return this._internalTexturesCache;
  12603. };
  12604. /**
  12605. * Gets the object containing all engine capabilities
  12606. * @returns the EngineCapabilities object
  12607. */
  12608. Engine.prototype.getCaps = function () {
  12609. return this._caps;
  12610. };
  12611. Object.defineProperty(Engine.prototype, "drawCalls", {
  12612. /** @hidden */
  12613. get: function () {
  12614. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12615. return 0;
  12616. },
  12617. enumerable: true,
  12618. configurable: true
  12619. });
  12620. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12621. /** @hidden */
  12622. get: function () {
  12623. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12624. return null;
  12625. },
  12626. enumerable: true,
  12627. configurable: true
  12628. });
  12629. /**
  12630. * Gets the current depth function
  12631. * @returns a number defining the depth function
  12632. */
  12633. Engine.prototype.getDepthFunction = function () {
  12634. return this._depthCullingState.depthFunc;
  12635. };
  12636. /**
  12637. * Sets the current depth function
  12638. * @param depthFunc defines the function to use
  12639. */
  12640. Engine.prototype.setDepthFunction = function (depthFunc) {
  12641. this._depthCullingState.depthFunc = depthFunc;
  12642. };
  12643. /**
  12644. * Sets the current depth function to GREATER
  12645. */
  12646. Engine.prototype.setDepthFunctionToGreater = function () {
  12647. this._depthCullingState.depthFunc = this._gl.GREATER;
  12648. };
  12649. /**
  12650. * Sets the current depth function to GEQUAL
  12651. */
  12652. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12653. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12654. };
  12655. /**
  12656. * Sets the current depth function to LESS
  12657. */
  12658. Engine.prototype.setDepthFunctionToLess = function () {
  12659. this._depthCullingState.depthFunc = this._gl.LESS;
  12660. };
  12661. /**
  12662. * Sets the current depth function to LEQUAL
  12663. */
  12664. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12665. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12666. };
  12667. /**
  12668. * Gets a boolean indicating if stencil buffer is enabled
  12669. * @returns the current stencil buffer state
  12670. */
  12671. Engine.prototype.getStencilBuffer = function () {
  12672. return this._stencilState.stencilTest;
  12673. };
  12674. /**
  12675. * Enable or disable the stencil buffer
  12676. * @param enable defines if the stencil buffer must be enabled or disabled
  12677. */
  12678. Engine.prototype.setStencilBuffer = function (enable) {
  12679. this._stencilState.stencilTest = enable;
  12680. };
  12681. /**
  12682. * Gets the current stencil mask
  12683. * @returns a number defining the new stencil mask to use
  12684. */
  12685. Engine.prototype.getStencilMask = function () {
  12686. return this._stencilState.stencilMask;
  12687. };
  12688. /**
  12689. * Sets the current stencil mask
  12690. * @param mask defines the new stencil mask to use
  12691. */
  12692. Engine.prototype.setStencilMask = function (mask) {
  12693. this._stencilState.stencilMask = mask;
  12694. };
  12695. /**
  12696. * Gets the current stencil function
  12697. * @returns a number defining the stencil function to use
  12698. */
  12699. Engine.prototype.getStencilFunction = function () {
  12700. return this._stencilState.stencilFunc;
  12701. };
  12702. /**
  12703. * Gets the current stencil reference value
  12704. * @returns a number defining the stencil reference value to use
  12705. */
  12706. Engine.prototype.getStencilFunctionReference = function () {
  12707. return this._stencilState.stencilFuncRef;
  12708. };
  12709. /**
  12710. * Gets the current stencil mask
  12711. * @returns a number defining the stencil mask to use
  12712. */
  12713. Engine.prototype.getStencilFunctionMask = function () {
  12714. return this._stencilState.stencilFuncMask;
  12715. };
  12716. /**
  12717. * Sets the current stencil function
  12718. * @param stencilFunc defines the new stencil function to use
  12719. */
  12720. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12721. this._stencilState.stencilFunc = stencilFunc;
  12722. };
  12723. /**
  12724. * Sets the current stencil reference
  12725. * @param reference defines the new stencil reference to use
  12726. */
  12727. Engine.prototype.setStencilFunctionReference = function (reference) {
  12728. this._stencilState.stencilFuncRef = reference;
  12729. };
  12730. /**
  12731. * Sets the current stencil mask
  12732. * @param mask defines the new stencil mask to use
  12733. */
  12734. Engine.prototype.setStencilFunctionMask = function (mask) {
  12735. this._stencilState.stencilFuncMask = mask;
  12736. };
  12737. /**
  12738. * Gets the current stencil operation when stencil fails
  12739. * @returns a number defining stencil operation to use when stencil fails
  12740. */
  12741. Engine.prototype.getStencilOperationFail = function () {
  12742. return this._stencilState.stencilOpStencilFail;
  12743. };
  12744. /**
  12745. * Gets the current stencil operation when depth fails
  12746. * @returns a number defining stencil operation to use when depth fails
  12747. */
  12748. Engine.prototype.getStencilOperationDepthFail = function () {
  12749. return this._stencilState.stencilOpDepthFail;
  12750. };
  12751. /**
  12752. * Gets the current stencil operation when stencil passes
  12753. * @returns a number defining stencil operation to use when stencil passes
  12754. */
  12755. Engine.prototype.getStencilOperationPass = function () {
  12756. return this._stencilState.stencilOpStencilDepthPass;
  12757. };
  12758. /**
  12759. * Sets the stencil operation to use when stencil fails
  12760. * @param operation defines the stencil operation to use when stencil fails
  12761. */
  12762. Engine.prototype.setStencilOperationFail = function (operation) {
  12763. this._stencilState.stencilOpStencilFail = operation;
  12764. };
  12765. /**
  12766. * Sets the stencil operation to use when depth fails
  12767. * @param operation defines the stencil operation to use when depth fails
  12768. */
  12769. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12770. this._stencilState.stencilOpDepthFail = operation;
  12771. };
  12772. /**
  12773. * Sets the stencil operation to use when stencil passes
  12774. * @param operation defines the stencil operation to use when stencil passes
  12775. */
  12776. Engine.prototype.setStencilOperationPass = function (operation) {
  12777. this._stencilState.stencilOpStencilDepthPass = operation;
  12778. };
  12779. /**
  12780. * Sets a boolean indicating if the dithering state is enabled or disabled
  12781. * @param value defines the dithering state
  12782. */
  12783. Engine.prototype.setDitheringState = function (value) {
  12784. if (value) {
  12785. this._gl.enable(this._gl.DITHER);
  12786. }
  12787. else {
  12788. this._gl.disable(this._gl.DITHER);
  12789. }
  12790. };
  12791. /**
  12792. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12793. * @param value defines the rasterizer state
  12794. */
  12795. Engine.prototype.setRasterizerState = function (value) {
  12796. if (value) {
  12797. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12798. }
  12799. else {
  12800. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12801. }
  12802. };
  12803. /**
  12804. * stop executing a render loop function and remove it from the execution array
  12805. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12806. */
  12807. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12808. if (!renderFunction) {
  12809. this._activeRenderLoops = [];
  12810. return;
  12811. }
  12812. var index = this._activeRenderLoops.indexOf(renderFunction);
  12813. if (index >= 0) {
  12814. this._activeRenderLoops.splice(index, 1);
  12815. }
  12816. };
  12817. /** @hidden */
  12818. Engine.prototype._renderLoop = function () {
  12819. if (!this._contextWasLost) {
  12820. var shouldRender = true;
  12821. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12822. shouldRender = false;
  12823. }
  12824. if (shouldRender) {
  12825. // Start new frame
  12826. this.beginFrame();
  12827. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12828. var renderFunction = this._activeRenderLoops[index];
  12829. renderFunction();
  12830. }
  12831. // Present
  12832. this.endFrame();
  12833. }
  12834. }
  12835. if (this._activeRenderLoops.length > 0) {
  12836. // Register new frame
  12837. var requester = null;
  12838. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12839. requester = this._vrDisplay;
  12840. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12841. }
  12842. else {
  12843. this._renderingQueueLaunched = false;
  12844. }
  12845. };
  12846. /**
  12847. * Register and execute a render loop. The engine can have more than one render function
  12848. * @param renderFunction defines the function to continuously execute
  12849. */
  12850. Engine.prototype.runRenderLoop = function (renderFunction) {
  12851. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12852. return;
  12853. }
  12854. this._activeRenderLoops.push(renderFunction);
  12855. if (!this._renderingQueueLaunched) {
  12856. this._renderingQueueLaunched = true;
  12857. this._bindedRenderFunction = this._renderLoop.bind(this);
  12858. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12859. }
  12860. };
  12861. /**
  12862. * Toggle full screen mode
  12863. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12864. * @param options defines an option object to be sent to the requestFullscreen function
  12865. */
  12866. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12867. if (this.isFullscreen) {
  12868. BABYLON.Tools.ExitFullscreen();
  12869. }
  12870. else {
  12871. this._pointerLockRequested = requestPointerLock;
  12872. if (this._renderingCanvas) {
  12873. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12874. }
  12875. }
  12876. };
  12877. /**
  12878. * Clear the current render buffer or the current render target (if any is set up)
  12879. * @param color defines the color to use
  12880. * @param backBuffer defines if the back buffer must be cleared
  12881. * @param depth defines if the depth buffer must be cleared
  12882. * @param stencil defines if the stencil buffer must be cleared
  12883. */
  12884. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12885. if (stencil === void 0) { stencil = false; }
  12886. this.applyStates();
  12887. var mode = 0;
  12888. if (backBuffer && color) {
  12889. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12890. mode |= this._gl.COLOR_BUFFER_BIT;
  12891. }
  12892. if (depth) {
  12893. this._gl.clearDepth(1.0);
  12894. mode |= this._gl.DEPTH_BUFFER_BIT;
  12895. }
  12896. if (stencil) {
  12897. this._gl.clearStencil(0);
  12898. mode |= this._gl.STENCIL_BUFFER_BIT;
  12899. }
  12900. this._gl.clear(mode);
  12901. };
  12902. /**
  12903. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12904. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12905. * @param y defines the y-coordinate of the corner of the clear rectangle
  12906. * @param width defines the width of the clear rectangle
  12907. * @param height defines the height of the clear rectangle
  12908. * @param clearColor defines the clear color
  12909. */
  12910. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12911. var gl = this._gl;
  12912. // Save state
  12913. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12914. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12915. // Change state
  12916. gl.enable(gl.SCISSOR_TEST);
  12917. gl.scissor(x, y, width, height);
  12918. // Clear
  12919. this.clear(clearColor, true, true, true);
  12920. // Restore state
  12921. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12922. if (curScissor === true) {
  12923. gl.enable(gl.SCISSOR_TEST);
  12924. }
  12925. else {
  12926. gl.disable(gl.SCISSOR_TEST);
  12927. }
  12928. };
  12929. /** @hidden */
  12930. Engine.prototype._viewport = function (x, y, width, height) {
  12931. if (x !== this._viewportCached.x ||
  12932. y !== this._viewportCached.y ||
  12933. width !== this._viewportCached.z ||
  12934. height !== this._viewportCached.w) {
  12935. this._viewportCached.x = x;
  12936. this._viewportCached.y = y;
  12937. this._viewportCached.z = width;
  12938. this._viewportCached.w = height;
  12939. this._gl.viewport(x, y, width, height);
  12940. }
  12941. };
  12942. /**
  12943. * Set the WebGL's viewport
  12944. * @param viewport defines the viewport element to be used
  12945. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12946. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12947. */
  12948. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12949. var width = requiredWidth || this.getRenderWidth();
  12950. var height = requiredHeight || this.getRenderHeight();
  12951. var x = viewport.x || 0;
  12952. var y = viewport.y || 0;
  12953. this._cachedViewport = viewport;
  12954. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12955. };
  12956. /**
  12957. * Directly set the WebGL Viewport
  12958. * @param x defines the x coordinate of the viewport (in screen space)
  12959. * @param y defines the y coordinate of the viewport (in screen space)
  12960. * @param width defines the width of the viewport (in screen space)
  12961. * @param height defines the height of the viewport (in screen space)
  12962. * @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
  12963. */
  12964. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12965. var currentViewport = this._cachedViewport;
  12966. this._cachedViewport = null;
  12967. this._viewport(x, y, width, height);
  12968. return currentViewport;
  12969. };
  12970. /**
  12971. * Begin a new frame
  12972. */
  12973. Engine.prototype.beginFrame = function () {
  12974. this.onBeginFrameObservable.notifyObservers(this);
  12975. this._measureFps();
  12976. };
  12977. /**
  12978. * Enf the current frame
  12979. */
  12980. Engine.prototype.endFrame = function () {
  12981. // Force a flush in case we are using a bad OS.
  12982. if (this._badOS) {
  12983. this.flushFramebuffer();
  12984. }
  12985. // Submit frame to the vr device, if enabled
  12986. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12987. // TODO: We should only submit the frame if we read frameData successfully.
  12988. this._vrDisplay.submitFrame();
  12989. }
  12990. this.onEndFrameObservable.notifyObservers(this);
  12991. };
  12992. /**
  12993. * Resize the view according to the canvas' size
  12994. */
  12995. Engine.prototype.resize = function () {
  12996. // We're not resizing the size of the canvas while in VR mode & presenting
  12997. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12998. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12999. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13000. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13001. }
  13002. };
  13003. /**
  13004. * Force a specific size of the canvas
  13005. * @param width defines the new canvas' width
  13006. * @param height defines the new canvas' height
  13007. */
  13008. Engine.prototype.setSize = function (width, height) {
  13009. if (!this._renderingCanvas) {
  13010. return;
  13011. }
  13012. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13013. return;
  13014. }
  13015. this._renderingCanvas.width = width;
  13016. this._renderingCanvas.height = height;
  13017. for (var index = 0; index < this.scenes.length; index++) {
  13018. var scene = this.scenes[index];
  13019. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13020. var cam = scene.cameras[camIndex];
  13021. cam._currentRenderId = 0;
  13022. }
  13023. }
  13024. if (this.onResizeObservable.hasObservers) {
  13025. this.onResizeObservable.notifyObservers(this);
  13026. }
  13027. };
  13028. // WebVR functions
  13029. /**
  13030. * Gets a boolean indicating if a webVR device was detected
  13031. * @returns true if a webVR device was detected
  13032. */
  13033. Engine.prototype.isVRDevicePresent = function () {
  13034. return !!this._vrDisplay;
  13035. };
  13036. /**
  13037. * Gets the current webVR device
  13038. * @returns the current webVR device (or null)
  13039. */
  13040. Engine.prototype.getVRDevice = function () {
  13041. return this._vrDisplay;
  13042. };
  13043. /**
  13044. * Initializes a webVR display and starts listening to display change events
  13045. * The onVRDisplayChangedObservable will be notified upon these changes
  13046. * @returns The onVRDisplayChangedObservable
  13047. */
  13048. Engine.prototype.initWebVR = function () {
  13049. this.initWebVRAsync();
  13050. return this.onVRDisplayChangedObservable;
  13051. };
  13052. /**
  13053. * Initializes a webVR display and starts listening to display change events
  13054. * The onVRDisplayChangedObservable will be notified upon these changes
  13055. * @returns A promise containing a VRDisplay and if vr is supported
  13056. */
  13057. Engine.prototype.initWebVRAsync = function () {
  13058. var _this = this;
  13059. var notifyObservers = function () {
  13060. var eventArgs = {
  13061. vrDisplay: _this._vrDisplay,
  13062. vrSupported: _this._vrSupported
  13063. };
  13064. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13065. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13066. };
  13067. if (!this._onVrDisplayConnect) {
  13068. this._onVrDisplayConnect = function (event) {
  13069. _this._vrDisplay = event.display;
  13070. notifyObservers();
  13071. };
  13072. this._onVrDisplayDisconnect = function () {
  13073. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13074. _this._vrDisplay = undefined;
  13075. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13076. notifyObservers();
  13077. };
  13078. this._onVrDisplayPresentChange = function () {
  13079. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13080. };
  13081. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13082. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13083. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13084. }
  13085. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13086. this._webVRInitPromise.then(notifyObservers);
  13087. return this._webVRInitPromise;
  13088. };
  13089. /**
  13090. * Call this function to switch to webVR mode
  13091. * Will do nothing if webVR is not supported or if there is no webVR device
  13092. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13093. */
  13094. Engine.prototype.enableVR = function () {
  13095. var _this = this;
  13096. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13097. var onResolved = function () {
  13098. _this.onVRRequestPresentComplete.notifyObservers(true);
  13099. _this._onVRFullScreenTriggered();
  13100. };
  13101. var onRejected = function () {
  13102. _this.onVRRequestPresentComplete.notifyObservers(false);
  13103. };
  13104. this.onVRRequestPresentStart.notifyObservers(this);
  13105. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13106. }
  13107. };
  13108. /**
  13109. * Call this function to leave webVR mode
  13110. * Will do nothing if webVR is not supported or if there is no webVR device
  13111. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13112. */
  13113. Engine.prototype.disableVR = function () {
  13114. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13115. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13116. }
  13117. };
  13118. Engine.prototype._getVRDisplaysAsync = function () {
  13119. var _this = this;
  13120. return new Promise(function (res, rej) {
  13121. if (navigator.getVRDisplays) {
  13122. navigator.getVRDisplays().then(function (devices) {
  13123. _this._vrSupported = true;
  13124. // note that devices may actually be an empty array. This is fine;
  13125. // we expect this._vrDisplay to be undefined in this case.
  13126. _this._vrDisplay = devices[0];
  13127. res({
  13128. vrDisplay: _this._vrDisplay,
  13129. vrSupported: _this._vrSupported
  13130. });
  13131. });
  13132. }
  13133. else {
  13134. _this._vrDisplay = undefined;
  13135. _this._vrSupported = false;
  13136. res({
  13137. vrDisplay: _this._vrDisplay,
  13138. vrSupported: _this._vrSupported
  13139. });
  13140. }
  13141. });
  13142. };
  13143. /**
  13144. * Binds the frame buffer to the specified texture.
  13145. * @param texture The texture to render to or null for the default canvas
  13146. * @param faceIndex The face of the texture to render to in case of cube texture
  13147. * @param requiredWidth The width of the target to render to
  13148. * @param requiredHeight The height of the target to render to
  13149. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13150. * @param depthStencilTexture The depth stencil texture to use to render
  13151. * @param lodLevel defines le lod level to bind to the frame buffer
  13152. */
  13153. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13154. if (lodLevel === void 0) { lodLevel = 0; }
  13155. if (this._currentRenderTarget) {
  13156. this.unBindFramebuffer(this._currentRenderTarget);
  13157. }
  13158. this._currentRenderTarget = texture;
  13159. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13160. var gl = this._gl;
  13161. if (texture.isCube) {
  13162. if (faceIndex === undefined) {
  13163. faceIndex = 0;
  13164. }
  13165. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13166. if (depthStencilTexture) {
  13167. if (depthStencilTexture._generateStencilBuffer) {
  13168. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13169. }
  13170. else {
  13171. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13172. }
  13173. }
  13174. }
  13175. if (this._cachedViewport && !forceFullscreenViewport) {
  13176. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13177. }
  13178. else {
  13179. if (!requiredWidth) {
  13180. requiredWidth = texture.width;
  13181. if (lodLevel) {
  13182. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13183. }
  13184. }
  13185. if (!requiredHeight) {
  13186. requiredHeight = texture.height;
  13187. if (lodLevel) {
  13188. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13189. }
  13190. }
  13191. this._viewport(0, 0, requiredWidth, requiredHeight);
  13192. }
  13193. this.wipeCaches();
  13194. };
  13195. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13196. if (this._currentFramebuffer !== framebuffer) {
  13197. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13198. this._currentFramebuffer = framebuffer;
  13199. }
  13200. };
  13201. /**
  13202. * Unbind the current render target texture from the webGL context
  13203. * @param texture defines the render target texture to unbind
  13204. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13205. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13206. */
  13207. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13208. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13209. this._currentRenderTarget = null;
  13210. // If MSAA, we need to bitblt back to main texture
  13211. var gl = this._gl;
  13212. if (texture._MSAAFramebuffer) {
  13213. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13214. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13215. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13216. }
  13217. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13218. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13219. gl.generateMipmap(gl.TEXTURE_2D);
  13220. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13221. }
  13222. if (onBeforeUnbind) {
  13223. if (texture._MSAAFramebuffer) {
  13224. // Bind the correct framebuffer
  13225. this.bindUnboundFramebuffer(texture._framebuffer);
  13226. }
  13227. onBeforeUnbind();
  13228. }
  13229. this.bindUnboundFramebuffer(null);
  13230. };
  13231. /**
  13232. * Unbind a list of render target textures from the webGL context
  13233. * This is used only when drawBuffer extension or webGL2 are active
  13234. * @param textures defines the render target textures to unbind
  13235. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13236. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13237. */
  13238. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13239. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13240. this._currentRenderTarget = null;
  13241. // If MSAA, we need to bitblt back to main texture
  13242. var gl = this._gl;
  13243. if (textures[0]._MSAAFramebuffer) {
  13244. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13245. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13246. var attachments = textures[0]._attachments;
  13247. if (!attachments) {
  13248. attachments = new Array(textures.length);
  13249. textures[0]._attachments = attachments;
  13250. }
  13251. for (var i = 0; i < textures.length; i++) {
  13252. var texture = textures[i];
  13253. for (var j = 0; j < attachments.length; j++) {
  13254. attachments[j] = gl.NONE;
  13255. }
  13256. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13257. gl.readBuffer(attachments[i]);
  13258. gl.drawBuffers(attachments);
  13259. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13260. }
  13261. for (var i = 0; i < attachments.length; i++) {
  13262. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13263. }
  13264. gl.drawBuffers(attachments);
  13265. }
  13266. for (var i = 0; i < textures.length; i++) {
  13267. var texture = textures[i];
  13268. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13269. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13270. gl.generateMipmap(gl.TEXTURE_2D);
  13271. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13272. }
  13273. }
  13274. if (onBeforeUnbind) {
  13275. if (textures[0]._MSAAFramebuffer) {
  13276. // Bind the correct framebuffer
  13277. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13278. }
  13279. onBeforeUnbind();
  13280. }
  13281. this.bindUnboundFramebuffer(null);
  13282. };
  13283. /**
  13284. * Force the mipmap generation for the given render target texture
  13285. * @param texture defines the render target texture to use
  13286. */
  13287. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13288. if (texture.generateMipMaps) {
  13289. var gl = this._gl;
  13290. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13291. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13292. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13293. }
  13294. };
  13295. /**
  13296. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13297. */
  13298. Engine.prototype.flushFramebuffer = function () {
  13299. this._gl.flush();
  13300. };
  13301. /**
  13302. * Unbind the current render target and bind the default framebuffer
  13303. */
  13304. Engine.prototype.restoreDefaultFramebuffer = function () {
  13305. if (this._currentRenderTarget) {
  13306. this.unBindFramebuffer(this._currentRenderTarget);
  13307. }
  13308. else {
  13309. this.bindUnboundFramebuffer(null);
  13310. }
  13311. if (this._cachedViewport) {
  13312. this.setViewport(this._cachedViewport);
  13313. }
  13314. this.wipeCaches();
  13315. };
  13316. // UBOs
  13317. /**
  13318. * Create an uniform buffer
  13319. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13320. * @param elements defines the content of the uniform buffer
  13321. * @returns the webGL uniform buffer
  13322. */
  13323. Engine.prototype.createUniformBuffer = function (elements) {
  13324. var ubo = this._gl.createBuffer();
  13325. if (!ubo) {
  13326. throw new Error("Unable to create uniform buffer");
  13327. }
  13328. this.bindUniformBuffer(ubo);
  13329. if (elements instanceof Float32Array) {
  13330. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13331. }
  13332. else {
  13333. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13334. }
  13335. this.bindUniformBuffer(null);
  13336. ubo.references = 1;
  13337. return ubo;
  13338. };
  13339. /**
  13340. * Create a dynamic uniform buffer
  13341. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13342. * @param elements defines the content of the uniform buffer
  13343. * @returns the webGL uniform buffer
  13344. */
  13345. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13346. var ubo = this._gl.createBuffer();
  13347. if (!ubo) {
  13348. throw new Error("Unable to create dynamic uniform buffer");
  13349. }
  13350. this.bindUniformBuffer(ubo);
  13351. if (elements instanceof Float32Array) {
  13352. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13353. }
  13354. else {
  13355. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13356. }
  13357. this.bindUniformBuffer(null);
  13358. ubo.references = 1;
  13359. return ubo;
  13360. };
  13361. /**
  13362. * Update an existing uniform buffer
  13363. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13364. * @param uniformBuffer defines the target uniform buffer
  13365. * @param elements defines the content to update
  13366. * @param offset defines the offset in the uniform buffer where update should start
  13367. * @param count defines the size of the data to update
  13368. */
  13369. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13370. this.bindUniformBuffer(uniformBuffer);
  13371. if (offset === undefined) {
  13372. offset = 0;
  13373. }
  13374. if (count === undefined) {
  13375. if (elements instanceof Float32Array) {
  13376. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13377. }
  13378. else {
  13379. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13380. }
  13381. }
  13382. else {
  13383. if (elements instanceof Float32Array) {
  13384. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13385. }
  13386. else {
  13387. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13388. }
  13389. }
  13390. this.bindUniformBuffer(null);
  13391. };
  13392. // VBOs
  13393. Engine.prototype._resetVertexBufferBinding = function () {
  13394. this.bindArrayBuffer(null);
  13395. this._cachedVertexBuffers = null;
  13396. };
  13397. /**
  13398. * Creates a vertex buffer
  13399. * @param data the data for the vertex buffer
  13400. * @returns the new WebGL static buffer
  13401. */
  13402. Engine.prototype.createVertexBuffer = function (data) {
  13403. var vbo = this._gl.createBuffer();
  13404. if (!vbo) {
  13405. throw new Error("Unable to create vertex buffer");
  13406. }
  13407. this.bindArrayBuffer(vbo);
  13408. if (data instanceof Array) {
  13409. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13410. }
  13411. else {
  13412. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13413. }
  13414. this._resetVertexBufferBinding();
  13415. vbo.references = 1;
  13416. return vbo;
  13417. };
  13418. /**
  13419. * Creates a dynamic vertex buffer
  13420. * @param data the data for the dynamic vertex buffer
  13421. * @returns the new WebGL dynamic buffer
  13422. */
  13423. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13424. var vbo = this._gl.createBuffer();
  13425. if (!vbo) {
  13426. throw new Error("Unable to create dynamic vertex buffer");
  13427. }
  13428. this.bindArrayBuffer(vbo);
  13429. if (data instanceof Array) {
  13430. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13431. }
  13432. else {
  13433. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13434. }
  13435. this._resetVertexBufferBinding();
  13436. vbo.references = 1;
  13437. return vbo;
  13438. };
  13439. /**
  13440. * Update a dynamic index buffer
  13441. * @param indexBuffer defines the target index buffer
  13442. * @param indices defines the data to update
  13443. * @param offset defines the offset in the target index buffer where update should start
  13444. */
  13445. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13446. if (offset === void 0) { offset = 0; }
  13447. // Force cache update
  13448. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13449. this.bindIndexBuffer(indexBuffer);
  13450. var arrayBuffer;
  13451. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13452. arrayBuffer = indices;
  13453. }
  13454. else {
  13455. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13456. }
  13457. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13458. this._resetIndexBufferBinding();
  13459. };
  13460. /**
  13461. * Updates a dynamic vertex buffer.
  13462. * @param vertexBuffer the vertex buffer to update
  13463. * @param data the data used to update the vertex buffer
  13464. * @param byteOffset the byte offset of the data
  13465. * @param byteLength the byte length of the data
  13466. */
  13467. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13468. this.bindArrayBuffer(vertexBuffer);
  13469. if (byteOffset === undefined) {
  13470. byteOffset = 0;
  13471. }
  13472. if (byteLength === undefined) {
  13473. if (data instanceof Array) {
  13474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13475. }
  13476. else {
  13477. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13478. }
  13479. }
  13480. else {
  13481. if (data instanceof Array) {
  13482. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13483. }
  13484. else {
  13485. if (data instanceof ArrayBuffer) {
  13486. data = new Uint8Array(data, byteOffset, byteLength);
  13487. }
  13488. else {
  13489. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13490. }
  13491. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13492. }
  13493. }
  13494. this._resetVertexBufferBinding();
  13495. };
  13496. Engine.prototype._resetIndexBufferBinding = function () {
  13497. this.bindIndexBuffer(null);
  13498. this._cachedIndexBuffer = null;
  13499. };
  13500. /**
  13501. * Creates a new index buffer
  13502. * @param indices defines the content of the index buffer
  13503. * @param updatable defines if the index buffer must be updatable
  13504. * @returns a new webGL buffer
  13505. */
  13506. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13507. var vbo = this._gl.createBuffer();
  13508. if (!vbo) {
  13509. throw new Error("Unable to create index buffer");
  13510. }
  13511. this.bindIndexBuffer(vbo);
  13512. // Check for 32 bits indices
  13513. var arrayBuffer;
  13514. var need32Bits = false;
  13515. if (indices instanceof Uint16Array) {
  13516. arrayBuffer = indices;
  13517. }
  13518. else {
  13519. //check 32 bit support
  13520. if (this._caps.uintIndices) {
  13521. if (indices instanceof Uint32Array) {
  13522. arrayBuffer = indices;
  13523. need32Bits = true;
  13524. }
  13525. else {
  13526. //number[] or Int32Array, check if 32 bit is necessary
  13527. for (var index = 0; index < indices.length; index++) {
  13528. if (indices[index] > 65535) {
  13529. need32Bits = true;
  13530. break;
  13531. }
  13532. }
  13533. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13534. }
  13535. }
  13536. else {
  13537. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13538. arrayBuffer = new Uint16Array(indices);
  13539. }
  13540. }
  13541. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13542. this._resetIndexBufferBinding();
  13543. vbo.references = 1;
  13544. vbo.is32Bits = need32Bits;
  13545. return vbo;
  13546. };
  13547. /**
  13548. * Bind a webGL buffer to the webGL context
  13549. * @param buffer defines the buffer to bind
  13550. */
  13551. Engine.prototype.bindArrayBuffer = function (buffer) {
  13552. if (!this._vaoRecordInProgress) {
  13553. this._unbindVertexArrayObject();
  13554. }
  13555. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13556. };
  13557. /**
  13558. * Bind an uniform buffer to the current webGL context
  13559. * @param buffer defines the buffer to bind
  13560. */
  13561. Engine.prototype.bindUniformBuffer = function (buffer) {
  13562. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13563. };
  13564. /**
  13565. * Bind a buffer to the current webGL context at a given location
  13566. * @param buffer defines the buffer to bind
  13567. * @param location defines the index where to bind the buffer
  13568. */
  13569. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13570. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13571. };
  13572. /**
  13573. * Bind a specific block at a given index in a specific shader program
  13574. * @param shaderProgram defines the shader program
  13575. * @param blockName defines the block name
  13576. * @param index defines the index where to bind the block
  13577. */
  13578. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13579. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13580. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13581. };
  13582. ;
  13583. Engine.prototype.bindIndexBuffer = function (buffer) {
  13584. if (!this._vaoRecordInProgress) {
  13585. this._unbindVertexArrayObject();
  13586. }
  13587. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13588. };
  13589. Engine.prototype.bindBuffer = function (buffer, target) {
  13590. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13591. this._gl.bindBuffer(target, buffer);
  13592. this._currentBoundBuffer[target] = buffer;
  13593. }
  13594. };
  13595. /**
  13596. * update the bound buffer with the given data
  13597. * @param data defines the data to update
  13598. */
  13599. Engine.prototype.updateArrayBuffer = function (data) {
  13600. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13601. };
  13602. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13603. var pointer = this._currentBufferPointers[indx];
  13604. var changed = false;
  13605. if (!pointer.active) {
  13606. changed = true;
  13607. pointer.active = true;
  13608. pointer.index = indx;
  13609. pointer.size = size;
  13610. pointer.type = type;
  13611. pointer.normalized = normalized;
  13612. pointer.stride = stride;
  13613. pointer.offset = offset;
  13614. pointer.buffer = buffer;
  13615. }
  13616. else {
  13617. if (pointer.buffer !== buffer) {
  13618. pointer.buffer = buffer;
  13619. changed = true;
  13620. }
  13621. if (pointer.size !== size) {
  13622. pointer.size = size;
  13623. changed = true;
  13624. }
  13625. if (pointer.type !== type) {
  13626. pointer.type = type;
  13627. changed = true;
  13628. }
  13629. if (pointer.normalized !== normalized) {
  13630. pointer.normalized = normalized;
  13631. changed = true;
  13632. }
  13633. if (pointer.stride !== stride) {
  13634. pointer.stride = stride;
  13635. changed = true;
  13636. }
  13637. if (pointer.offset !== offset) {
  13638. pointer.offset = offset;
  13639. changed = true;
  13640. }
  13641. }
  13642. if (changed || this._vaoRecordInProgress) {
  13643. this.bindArrayBuffer(buffer);
  13644. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13645. }
  13646. };
  13647. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13648. if (indexBuffer == null) {
  13649. return;
  13650. }
  13651. if (this._cachedIndexBuffer !== indexBuffer) {
  13652. this._cachedIndexBuffer = indexBuffer;
  13653. this.bindIndexBuffer(indexBuffer);
  13654. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13655. }
  13656. };
  13657. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13658. var attributes = effect.getAttributesNames();
  13659. if (!this._vaoRecordInProgress) {
  13660. this._unbindVertexArrayObject();
  13661. }
  13662. this.unbindAllAttributes();
  13663. for (var index = 0; index < attributes.length; index++) {
  13664. var order = effect.getAttributeLocation(index);
  13665. if (order >= 0) {
  13666. var vertexBuffer = vertexBuffers[attributes[index]];
  13667. if (!vertexBuffer) {
  13668. continue;
  13669. }
  13670. this._gl.enableVertexAttribArray(order);
  13671. if (!this._vaoRecordInProgress) {
  13672. this._vertexAttribArraysEnabled[order] = true;
  13673. }
  13674. var buffer = vertexBuffer.getBuffer();
  13675. if (buffer) {
  13676. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13677. if (vertexBuffer.getIsInstanced()) {
  13678. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13679. if (!this._vaoRecordInProgress) {
  13680. this._currentInstanceLocations.push(order);
  13681. this._currentInstanceBuffers.push(buffer);
  13682. }
  13683. }
  13684. }
  13685. }
  13686. }
  13687. };
  13688. /**
  13689. * Records a vertex array object
  13690. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13691. * @param vertexBuffers defines the list of vertex buffers to store
  13692. * @param indexBuffer defines the index buffer to store
  13693. * @param effect defines the effect to store
  13694. * @returns the new vertex array object
  13695. */
  13696. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13697. var vao = this._gl.createVertexArray();
  13698. this._vaoRecordInProgress = true;
  13699. this._gl.bindVertexArray(vao);
  13700. this._mustWipeVertexAttributes = true;
  13701. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13702. this.bindIndexBuffer(indexBuffer);
  13703. this._vaoRecordInProgress = false;
  13704. this._gl.bindVertexArray(null);
  13705. return vao;
  13706. };
  13707. /**
  13708. * Bind a specific vertex array object
  13709. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13710. * @param vertexArrayObject defines the vertex array object to bind
  13711. * @param indexBuffer defines the index buffer to bind
  13712. */
  13713. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13714. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13715. this._cachedVertexArrayObject = vertexArrayObject;
  13716. this._gl.bindVertexArray(vertexArrayObject);
  13717. this._cachedVertexBuffers = null;
  13718. this._cachedIndexBuffer = null;
  13719. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13720. this._mustWipeVertexAttributes = true;
  13721. }
  13722. };
  13723. /**
  13724. * Bind webGl buffers directly to the webGL context
  13725. * @param vertexBuffer defines the vertex buffer to bind
  13726. * @param indexBuffer defines the index buffer to bind
  13727. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13728. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13729. * @param effect defines the effect associated with the vertex buffer
  13730. */
  13731. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13732. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13733. this._cachedVertexBuffers = vertexBuffer;
  13734. this._cachedEffectForVertexBuffers = effect;
  13735. var attributesCount = effect.getAttributesCount();
  13736. this._unbindVertexArrayObject();
  13737. this.unbindAllAttributes();
  13738. var offset = 0;
  13739. for (var index = 0; index < attributesCount; index++) {
  13740. if (index < vertexDeclaration.length) {
  13741. var order = effect.getAttributeLocation(index);
  13742. if (order >= 0) {
  13743. this._gl.enableVertexAttribArray(order);
  13744. this._vertexAttribArraysEnabled[order] = true;
  13745. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13746. }
  13747. offset += vertexDeclaration[index] * 4;
  13748. }
  13749. }
  13750. }
  13751. this._bindIndexBufferWithCache(indexBuffer);
  13752. };
  13753. Engine.prototype._unbindVertexArrayObject = function () {
  13754. if (!this._cachedVertexArrayObject) {
  13755. return;
  13756. }
  13757. this._cachedVertexArrayObject = null;
  13758. this._gl.bindVertexArray(null);
  13759. };
  13760. /**
  13761. * Bind a list of vertex buffers to the webGL context
  13762. * @param vertexBuffers defines the list of vertex buffers to bind
  13763. * @param indexBuffer defines the index buffer to bind
  13764. * @param effect defines the effect associated with the vertex buffers
  13765. */
  13766. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13767. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13768. this._cachedVertexBuffers = vertexBuffers;
  13769. this._cachedEffectForVertexBuffers = effect;
  13770. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13771. }
  13772. this._bindIndexBufferWithCache(indexBuffer);
  13773. };
  13774. /**
  13775. * Unbind all instance attributes
  13776. */
  13777. Engine.prototype.unbindInstanceAttributes = function () {
  13778. var boundBuffer;
  13779. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13780. var instancesBuffer = this._currentInstanceBuffers[i];
  13781. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13782. boundBuffer = instancesBuffer;
  13783. this.bindArrayBuffer(instancesBuffer);
  13784. }
  13785. var offsetLocation = this._currentInstanceLocations[i];
  13786. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13787. }
  13788. this._currentInstanceBuffers.length = 0;
  13789. this._currentInstanceLocations.length = 0;
  13790. };
  13791. /**
  13792. * Release and free the memory of a vertex array object
  13793. * @param vao defines the vertex array object to delete
  13794. */
  13795. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13796. this._gl.deleteVertexArray(vao);
  13797. };
  13798. /** @hidden */
  13799. Engine.prototype._releaseBuffer = function (buffer) {
  13800. buffer.references--;
  13801. if (buffer.references === 0) {
  13802. this._gl.deleteBuffer(buffer);
  13803. return true;
  13804. }
  13805. return false;
  13806. };
  13807. /**
  13808. * Creates a webGL buffer to use with instanciation
  13809. * @param capacity defines the size of the buffer
  13810. * @returns the webGL buffer
  13811. */
  13812. Engine.prototype.createInstancesBuffer = function (capacity) {
  13813. var buffer = this._gl.createBuffer();
  13814. if (!buffer) {
  13815. throw new Error("Unable to create instance buffer");
  13816. }
  13817. buffer.capacity = capacity;
  13818. this.bindArrayBuffer(buffer);
  13819. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13820. return buffer;
  13821. };
  13822. /**
  13823. * Delete a webGL buffer used with instanciation
  13824. * @param buffer defines the webGL buffer to delete
  13825. */
  13826. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13827. this._gl.deleteBuffer(buffer);
  13828. };
  13829. /**
  13830. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13831. * @param instancesBuffer defines the webGL buffer to update and bind
  13832. * @param data defines the data to store in the buffer
  13833. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13834. */
  13835. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13836. this.bindArrayBuffer(instancesBuffer);
  13837. if (data) {
  13838. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13839. }
  13840. if (offsetLocations[0].index !== undefined) {
  13841. var stride = 0;
  13842. for (var i = 0; i < offsetLocations.length; i++) {
  13843. var ai = offsetLocations[i];
  13844. stride += ai.attributeSize * 4;
  13845. }
  13846. for (var i = 0; i < offsetLocations.length; i++) {
  13847. var ai = offsetLocations[i];
  13848. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13849. this._gl.enableVertexAttribArray(ai.index);
  13850. this._vertexAttribArraysEnabled[ai.index] = true;
  13851. }
  13852. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13853. this._gl.vertexAttribDivisor(ai.index, 1);
  13854. this._currentInstanceLocations.push(ai.index);
  13855. this._currentInstanceBuffers.push(instancesBuffer);
  13856. }
  13857. }
  13858. else {
  13859. for (var index = 0; index < 4; index++) {
  13860. var offsetLocation = offsetLocations[index];
  13861. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13862. this._gl.enableVertexAttribArray(offsetLocation);
  13863. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13864. }
  13865. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13866. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13867. this._currentInstanceLocations.push(offsetLocation);
  13868. this._currentInstanceBuffers.push(instancesBuffer);
  13869. }
  13870. }
  13871. };
  13872. /**
  13873. * Apply all cached states (depth, culling, stencil and alpha)
  13874. */
  13875. Engine.prototype.applyStates = function () {
  13876. this._depthCullingState.apply(this._gl);
  13877. this._stencilState.apply(this._gl);
  13878. this._alphaState.apply(this._gl);
  13879. };
  13880. /**
  13881. * Send a draw order
  13882. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13883. * @param indexStart defines the starting index
  13884. * @param indexCount defines the number of index to draw
  13885. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13886. */
  13887. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13888. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13889. };
  13890. /**
  13891. * Draw a list of points
  13892. * @param verticesStart defines the index of first vertex to draw
  13893. * @param verticesCount defines the count of vertices to draw
  13894. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13895. */
  13896. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13897. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13898. };
  13899. /**
  13900. * Draw a list of unindexed primitives
  13901. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13902. * @param verticesStart defines the index of first vertex to draw
  13903. * @param verticesCount defines the count of vertices to draw
  13904. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13905. */
  13906. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13907. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13908. };
  13909. /**
  13910. * Draw a list of indexed primitives
  13911. * @param fillMode defines the primitive to use
  13912. * @param indexStart defines the starting index
  13913. * @param indexCount defines the number of index to draw
  13914. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13915. */
  13916. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13917. // Apply states
  13918. this.applyStates();
  13919. this._drawCalls.addCount(1, false);
  13920. // Render
  13921. var drawMode = this._drawMode(fillMode);
  13922. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13923. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13924. if (instancesCount) {
  13925. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13926. }
  13927. else {
  13928. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13929. }
  13930. };
  13931. /**
  13932. * Draw a list of unindexed primitives
  13933. * @param fillMode defines the primitive to use
  13934. * @param verticesStart defines the index of first vertex to draw
  13935. * @param verticesCount defines the count of vertices to draw
  13936. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13937. */
  13938. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13939. // Apply states
  13940. this.applyStates();
  13941. this._drawCalls.addCount(1, false);
  13942. var drawMode = this._drawMode(fillMode);
  13943. if (instancesCount) {
  13944. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13945. }
  13946. else {
  13947. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13948. }
  13949. };
  13950. Engine.prototype._drawMode = function (fillMode) {
  13951. switch (fillMode) {
  13952. // Triangle views
  13953. case BABYLON.Material.TriangleFillMode:
  13954. return this._gl.TRIANGLES;
  13955. case BABYLON.Material.PointFillMode:
  13956. return this._gl.POINTS;
  13957. case BABYLON.Material.WireFrameFillMode:
  13958. return this._gl.LINES;
  13959. // Draw modes
  13960. case BABYLON.Material.PointListDrawMode:
  13961. return this._gl.POINTS;
  13962. case BABYLON.Material.LineListDrawMode:
  13963. return this._gl.LINES;
  13964. case BABYLON.Material.LineLoopDrawMode:
  13965. return this._gl.LINE_LOOP;
  13966. case BABYLON.Material.LineStripDrawMode:
  13967. return this._gl.LINE_STRIP;
  13968. case BABYLON.Material.TriangleStripDrawMode:
  13969. return this._gl.TRIANGLE_STRIP;
  13970. case BABYLON.Material.TriangleFanDrawMode:
  13971. return this._gl.TRIANGLE_FAN;
  13972. default:
  13973. return this._gl.TRIANGLES;
  13974. }
  13975. };
  13976. // Shaders
  13977. /** @hidden */
  13978. Engine.prototype._releaseEffect = function (effect) {
  13979. if (this._compiledEffects[effect._key]) {
  13980. delete this._compiledEffects[effect._key];
  13981. this._deleteProgram(effect.getProgram());
  13982. }
  13983. };
  13984. /** @hidden */
  13985. Engine.prototype._deleteProgram = function (program) {
  13986. if (program) {
  13987. program.__SPECTOR_rebuildProgram = null;
  13988. if (program.transformFeedback) {
  13989. this.deleteTransformFeedback(program.transformFeedback);
  13990. program.transformFeedback = null;
  13991. }
  13992. this._gl.deleteProgram(program);
  13993. }
  13994. };
  13995. /**
  13996. * Create a new effect (used to store vertex/fragment shaders)
  13997. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13998. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13999. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14000. * @param samplers defines an array of string used to represent textures
  14001. * @param defines defines the string containing the defines to use to compile the shaders
  14002. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14003. * @param onCompiled defines a function to call when the effect creation is successful
  14004. * @param onError defines a function to call when the effect creation has failed
  14005. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14006. * @returns the new Effect
  14007. */
  14008. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14009. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14010. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14011. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14012. if (this._compiledEffects[name]) {
  14013. var compiledEffect = this._compiledEffects[name];
  14014. if (onCompiled && compiledEffect.isReady()) {
  14015. onCompiled(compiledEffect);
  14016. }
  14017. return compiledEffect;
  14018. }
  14019. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14020. effect._key = name;
  14021. this._compiledEffects[name] = effect;
  14022. return effect;
  14023. };
  14024. /**
  14025. * Create an effect to use with particle systems.
  14026. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14027. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14028. * @param uniformsNames defines a list of attribute names
  14029. * @param samplers defines an array of string used to represent textures
  14030. * @param defines defines the string containing the defines to use to compile the shaders
  14031. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14032. * @param onCompiled defines a function to call when the effect creation is successful
  14033. * @param onError defines a function to call when the effect creation has failed
  14034. * @returns the new Effect
  14035. */
  14036. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14037. if (uniformsNames === void 0) { uniformsNames = []; }
  14038. if (samplers === void 0) { samplers = []; }
  14039. if (defines === void 0) { defines = ""; }
  14040. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14041. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14042. if (defines.indexOf(" BILLBOARD") === -1) {
  14043. defines += "\n#define BILLBOARD\n";
  14044. }
  14045. if (samplers.indexOf("diffuseSampler") === -1) {
  14046. samplers.push("diffuseSampler");
  14047. }
  14048. return this.createEffect({
  14049. vertex: "particles",
  14050. fragmentElement: fragmentName
  14051. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14052. };
  14053. /**
  14054. * Directly creates a webGL program
  14055. * @param vertexCode defines the vertex shader code to use
  14056. * @param fragmentCode defines the fragment shader code to use
  14057. * @param context defines the webGL context to use (if not set, the current one will be used)
  14058. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14059. * @returns the new webGL program
  14060. */
  14061. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14062. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14063. context = context || this._gl;
  14064. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14065. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14066. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14067. };
  14068. /**
  14069. * Creates a webGL program
  14070. * @param vertexCode defines the vertex shader code to use
  14071. * @param fragmentCode defines the fragment shader code to use
  14072. * @param defines defines the string containing the defines to use to compile the shaders
  14073. * @param context defines the webGL context to use (if not set, the current one will be used)
  14074. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14075. * @returns the new webGL program
  14076. */
  14077. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14078. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14079. context = context || this._gl;
  14080. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14081. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14082. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14083. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14084. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14085. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14086. return program;
  14087. };
  14088. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14089. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14090. var shaderProgram = context.createProgram();
  14091. if (!shaderProgram) {
  14092. throw new Error("Unable to create program");
  14093. }
  14094. context.attachShader(shaderProgram, vertexShader);
  14095. context.attachShader(shaderProgram, fragmentShader);
  14096. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14097. var transformFeedback = this.createTransformFeedback();
  14098. this.bindTransformFeedback(transformFeedback);
  14099. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14100. shaderProgram.transformFeedback = transformFeedback;
  14101. }
  14102. context.linkProgram(shaderProgram);
  14103. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14104. this.bindTransformFeedback(null);
  14105. }
  14106. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14107. if (!linked) {
  14108. var error = context.getProgramInfoLog(shaderProgram);
  14109. if (error) {
  14110. throw new Error(error);
  14111. }
  14112. }
  14113. if (this.validateShaderPrograms) {
  14114. context.validateProgram(shaderProgram);
  14115. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14116. if (!validated) {
  14117. var error = context.getProgramInfoLog(shaderProgram);
  14118. if (error) {
  14119. throw new Error(error);
  14120. }
  14121. }
  14122. }
  14123. context.deleteShader(vertexShader);
  14124. context.deleteShader(fragmentShader);
  14125. return shaderProgram;
  14126. };
  14127. /**
  14128. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14129. * @param shaderProgram defines the webGL program to use
  14130. * @param uniformsNames defines the list of uniform names
  14131. * @returns an array of webGL uniform locations
  14132. */
  14133. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14134. var results = new Array();
  14135. for (var index = 0; index < uniformsNames.length; index++) {
  14136. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14137. }
  14138. return results;
  14139. };
  14140. /**
  14141. * Gets the lsit of active attributes for a given webGL program
  14142. * @param shaderProgram defines the webGL program to use
  14143. * @param attributesNames defines the list of attribute names to get
  14144. * @returns an array of indices indicating the offset of each attribute
  14145. */
  14146. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14147. var results = [];
  14148. for (var index = 0; index < attributesNames.length; index++) {
  14149. try {
  14150. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14151. }
  14152. catch (e) {
  14153. results.push(-1);
  14154. }
  14155. }
  14156. return results;
  14157. };
  14158. /**
  14159. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14160. * @param effect defines the effect to activate
  14161. */
  14162. Engine.prototype.enableEffect = function (effect) {
  14163. if (!effect) {
  14164. return;
  14165. }
  14166. // Use program
  14167. this.bindSamplers(effect);
  14168. this._currentEffect = effect;
  14169. if (effect.onBind) {
  14170. effect.onBind(effect);
  14171. }
  14172. effect.onBindObservable.notifyObservers(effect);
  14173. };
  14174. /**
  14175. * Set the value of an uniform to an array of int32
  14176. * @param uniform defines the webGL uniform location where to store the value
  14177. * @param array defines the array of int32 to store
  14178. */
  14179. Engine.prototype.setIntArray = function (uniform, array) {
  14180. if (!uniform)
  14181. return;
  14182. this._gl.uniform1iv(uniform, array);
  14183. };
  14184. /**
  14185. * Set the value of an uniform to an array of int32 (stored as vec2)
  14186. * @param uniform defines the webGL uniform location where to store the value
  14187. * @param array defines the array of int32 to store
  14188. */
  14189. Engine.prototype.setIntArray2 = function (uniform, array) {
  14190. if (!uniform || array.length % 2 !== 0)
  14191. return;
  14192. this._gl.uniform2iv(uniform, array);
  14193. };
  14194. /**
  14195. * Set the value of an uniform to an array of int32 (stored as vec3)
  14196. * @param uniform defines the webGL uniform location where to store the value
  14197. * @param array defines the array of int32 to store
  14198. */
  14199. Engine.prototype.setIntArray3 = function (uniform, array) {
  14200. if (!uniform || array.length % 3 !== 0)
  14201. return;
  14202. this._gl.uniform3iv(uniform, array);
  14203. };
  14204. /**
  14205. * Set the value of an uniform to an array of int32 (stored as vec4)
  14206. * @param uniform defines the webGL uniform location where to store the value
  14207. * @param array defines the array of int32 to store
  14208. */
  14209. Engine.prototype.setIntArray4 = function (uniform, array) {
  14210. if (!uniform || array.length % 4 !== 0)
  14211. return;
  14212. this._gl.uniform4iv(uniform, array);
  14213. };
  14214. /**
  14215. * Set the value of an uniform to an array of float32
  14216. * @param uniform defines the webGL uniform location where to store the value
  14217. * @param array defines the array of float32 to store
  14218. */
  14219. Engine.prototype.setFloatArray = function (uniform, array) {
  14220. if (!uniform)
  14221. return;
  14222. this._gl.uniform1fv(uniform, array);
  14223. };
  14224. /**
  14225. * Set the value of an uniform to an array of float32 (stored as vec2)
  14226. * @param uniform defines the webGL uniform location where to store the value
  14227. * @param array defines the array of float32 to store
  14228. */
  14229. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14230. if (!uniform || array.length % 2 !== 0)
  14231. return;
  14232. this._gl.uniform2fv(uniform, array);
  14233. };
  14234. /**
  14235. * Set the value of an uniform to an array of float32 (stored as vec3)
  14236. * @param uniform defines the webGL uniform location where to store the value
  14237. * @param array defines the array of float32 to store
  14238. */
  14239. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14240. if (!uniform || array.length % 3 !== 0)
  14241. return;
  14242. this._gl.uniform3fv(uniform, array);
  14243. };
  14244. /**
  14245. * Set the value of an uniform to an array of float32 (stored as vec4)
  14246. * @param uniform defines the webGL uniform location where to store the value
  14247. * @param array defines the array of float32 to store
  14248. */
  14249. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14250. if (!uniform || array.length % 4 !== 0)
  14251. return;
  14252. this._gl.uniform4fv(uniform, array);
  14253. };
  14254. /**
  14255. * Set the value of an uniform to an array of number
  14256. * @param uniform defines the webGL uniform location where to store the value
  14257. * @param array defines the array of number to store
  14258. */
  14259. Engine.prototype.setArray = function (uniform, array) {
  14260. if (!uniform)
  14261. return;
  14262. this._gl.uniform1fv(uniform, array);
  14263. };
  14264. /**
  14265. * Set the value of an uniform to an array of number (stored as vec2)
  14266. * @param uniform defines the webGL uniform location where to store the value
  14267. * @param array defines the array of number to store
  14268. */
  14269. Engine.prototype.setArray2 = function (uniform, array) {
  14270. if (!uniform || array.length % 2 !== 0)
  14271. return;
  14272. this._gl.uniform2fv(uniform, array);
  14273. };
  14274. /**
  14275. * Set the value of an uniform to an array of number (stored as vec3)
  14276. * @param uniform defines the webGL uniform location where to store the value
  14277. * @param array defines the array of number to store
  14278. */
  14279. Engine.prototype.setArray3 = function (uniform, array) {
  14280. if (!uniform || array.length % 3 !== 0)
  14281. return;
  14282. this._gl.uniform3fv(uniform, array);
  14283. };
  14284. /**
  14285. * Set the value of an uniform to an array of number (stored as vec4)
  14286. * @param uniform defines the webGL uniform location where to store the value
  14287. * @param array defines the array of number to store
  14288. */
  14289. Engine.prototype.setArray4 = function (uniform, array) {
  14290. if (!uniform || array.length % 4 !== 0)
  14291. return;
  14292. this._gl.uniform4fv(uniform, array);
  14293. };
  14294. /**
  14295. * Set the value of an uniform to an array of float32 (stored as matrices)
  14296. * @param uniform defines the webGL uniform location where to store the value
  14297. * @param matrices defines the array of float32 to store
  14298. */
  14299. Engine.prototype.setMatrices = function (uniform, matrices) {
  14300. if (!uniform)
  14301. return;
  14302. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14303. };
  14304. /**
  14305. * Set the value of an uniform to a matrix
  14306. * @param uniform defines the webGL uniform location where to store the value
  14307. * @param matrix defines the matrix to store
  14308. */
  14309. Engine.prototype.setMatrix = function (uniform, matrix) {
  14310. if (!uniform)
  14311. return;
  14312. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14313. };
  14314. /**
  14315. * Set the value of an uniform to a matrix (3x3)
  14316. * @param uniform defines the webGL uniform location where to store the value
  14317. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14318. */
  14319. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14320. if (!uniform)
  14321. return;
  14322. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14323. };
  14324. /**
  14325. * Set the value of an uniform to a matrix (2x2)
  14326. * @param uniform defines the webGL uniform location where to store the value
  14327. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14328. */
  14329. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14330. if (!uniform)
  14331. return;
  14332. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14333. };
  14334. /**
  14335. * Set the value of an uniform to a number (int)
  14336. * @param uniform defines the webGL uniform location where to store the value
  14337. * @param value defines the int number to store
  14338. */
  14339. Engine.prototype.setInt = function (uniform, value) {
  14340. if (!uniform)
  14341. return;
  14342. this._gl.uniform1i(uniform, value);
  14343. };
  14344. /**
  14345. * Set the value of an uniform to a number (float)
  14346. * @param uniform defines the webGL uniform location where to store the value
  14347. * @param value defines the float number to store
  14348. */
  14349. Engine.prototype.setFloat = function (uniform, value) {
  14350. if (!uniform)
  14351. return;
  14352. this._gl.uniform1f(uniform, value);
  14353. };
  14354. /**
  14355. * Set the value of an uniform to a vec2
  14356. * @param uniform defines the webGL uniform location where to store the value
  14357. * @param x defines the 1st component of the value
  14358. * @param y defines the 2nd component of the value
  14359. */
  14360. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14361. if (!uniform)
  14362. return;
  14363. this._gl.uniform2f(uniform, x, y);
  14364. };
  14365. /**
  14366. * Set the value of an uniform to a vec3
  14367. * @param uniform defines the webGL uniform location where to store the value
  14368. * @param x defines the 1st component of the value
  14369. * @param y defines the 2nd component of the value
  14370. * @param z defines the 3rd component of the value
  14371. */
  14372. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14373. if (!uniform)
  14374. return;
  14375. this._gl.uniform3f(uniform, x, y, z);
  14376. };
  14377. /**
  14378. * Set the value of an uniform to a boolean
  14379. * @param uniform defines the webGL uniform location where to store the value
  14380. * @param bool defines the boolean to store
  14381. */
  14382. Engine.prototype.setBool = function (uniform, bool) {
  14383. if (!uniform)
  14384. return;
  14385. this._gl.uniform1i(uniform, bool);
  14386. };
  14387. /**
  14388. * Set the value of an uniform to a vec4
  14389. * @param uniform defines the webGL uniform location where to store the value
  14390. * @param x defines the 1st component of the value
  14391. * @param y defines the 2nd component of the value
  14392. * @param z defines the 3rd component of the value
  14393. * @param w defines the 4th component of the value
  14394. */
  14395. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14396. if (!uniform)
  14397. return;
  14398. this._gl.uniform4f(uniform, x, y, z, w);
  14399. };
  14400. /**
  14401. * Set the value of an uniform to a Color3
  14402. * @param uniform defines the webGL uniform location where to store the value
  14403. * @param color3 defines the color to store
  14404. */
  14405. Engine.prototype.setColor3 = function (uniform, color3) {
  14406. if (!uniform)
  14407. return;
  14408. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14409. };
  14410. /**
  14411. * Set the value of an uniform to a Color3 and an alpha value
  14412. * @param uniform defines the webGL uniform location where to store the value
  14413. * @param color3 defines the color to store
  14414. * @param alpha defines the alpha component to store
  14415. */
  14416. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14417. if (!uniform)
  14418. return;
  14419. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14420. };
  14421. /**
  14422. * Sets a Color4 on a uniform variable
  14423. * @param uniform defines the uniform location
  14424. * @param color4 defines the value to be set
  14425. */
  14426. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14427. if (!uniform)
  14428. return;
  14429. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14430. };
  14431. // States
  14432. /**
  14433. * Set various states to the webGL context
  14434. * @param culling defines backface culling state
  14435. * @param zOffset defines the value to apply to zOffset (0 by default)
  14436. * @param force defines if states must be applied even if cache is up to date
  14437. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14438. */
  14439. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14440. if (zOffset === void 0) { zOffset = 0; }
  14441. if (reverseSide === void 0) { reverseSide = false; }
  14442. // Culling
  14443. if (this._depthCullingState.cull !== culling || force) {
  14444. this._depthCullingState.cull = culling;
  14445. }
  14446. // Cull face
  14447. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14448. if (this._depthCullingState.cullFace !== cullFace || force) {
  14449. this._depthCullingState.cullFace = cullFace;
  14450. }
  14451. // Z offset
  14452. this.setZOffset(zOffset);
  14453. // Front face
  14454. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14455. if (this._depthCullingState.frontFace !== frontFace || force) {
  14456. this._depthCullingState.frontFace = frontFace;
  14457. }
  14458. };
  14459. /**
  14460. * Set the z offset to apply to current rendering
  14461. * @param value defines the offset to apply
  14462. */
  14463. Engine.prototype.setZOffset = function (value) {
  14464. this._depthCullingState.zOffset = value;
  14465. };
  14466. /**
  14467. * Gets the current value of the zOffset
  14468. * @returns the current zOffset state
  14469. */
  14470. Engine.prototype.getZOffset = function () {
  14471. return this._depthCullingState.zOffset;
  14472. };
  14473. /**
  14474. * Enable or disable depth buffering
  14475. * @param enable defines the state to set
  14476. */
  14477. Engine.prototype.setDepthBuffer = function (enable) {
  14478. this._depthCullingState.depthTest = enable;
  14479. };
  14480. /**
  14481. * Gets a boolean indicating if depth writing is enabled
  14482. * @returns the current depth writing state
  14483. */
  14484. Engine.prototype.getDepthWrite = function () {
  14485. return this._depthCullingState.depthMask;
  14486. };
  14487. /**
  14488. * Enable or disable depth writing
  14489. * @param enable defines the state to set
  14490. */
  14491. Engine.prototype.setDepthWrite = function (enable) {
  14492. this._depthCullingState.depthMask = enable;
  14493. };
  14494. /**
  14495. * Enable or disable color writing
  14496. * @param enable defines the state to set
  14497. */
  14498. Engine.prototype.setColorWrite = function (enable) {
  14499. this._gl.colorMask(enable, enable, enable, enable);
  14500. this._colorWrite = enable;
  14501. };
  14502. /**
  14503. * Gets a boolean indicating if color writing is enabled
  14504. * @returns the current color writing state
  14505. */
  14506. Engine.prototype.getColorWrite = function () {
  14507. return this._colorWrite;
  14508. };
  14509. /**
  14510. * Sets alpha constants used by some alpha blending modes
  14511. * @param r defines the red component
  14512. * @param g defines the green component
  14513. * @param b defines the blue component
  14514. * @param a defines the alpha component
  14515. */
  14516. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14517. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14518. };
  14519. /**
  14520. * Sets the current alpha mode
  14521. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14522. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14523. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14524. */
  14525. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14526. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14527. if (this._alphaMode === mode) {
  14528. return;
  14529. }
  14530. switch (mode) {
  14531. case Engine.ALPHA_DISABLE:
  14532. this._alphaState.alphaBlend = false;
  14533. break;
  14534. case Engine.ALPHA_PREMULTIPLIED:
  14535. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14536. this._alphaState.alphaBlend = true;
  14537. break;
  14538. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14539. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14540. this._alphaState.alphaBlend = true;
  14541. break;
  14542. case Engine.ALPHA_COMBINE:
  14543. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14544. this._alphaState.alphaBlend = true;
  14545. break;
  14546. case Engine.ALPHA_ONEONE:
  14547. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14548. this._alphaState.alphaBlend = true;
  14549. break;
  14550. case Engine.ALPHA_ADD:
  14551. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14552. this._alphaState.alphaBlend = true;
  14553. break;
  14554. case Engine.ALPHA_SUBTRACT:
  14555. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14556. this._alphaState.alphaBlend = true;
  14557. break;
  14558. case Engine.ALPHA_MULTIPLY:
  14559. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14560. this._alphaState.alphaBlend = true;
  14561. break;
  14562. case Engine.ALPHA_MAXIMIZED:
  14563. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14564. this._alphaState.alphaBlend = true;
  14565. break;
  14566. case Engine.ALPHA_INTERPOLATE:
  14567. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14568. this._alphaState.alphaBlend = true;
  14569. break;
  14570. case Engine.ALPHA_SCREENMODE:
  14571. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14572. this._alphaState.alphaBlend = true;
  14573. break;
  14574. }
  14575. if (!noDepthWriteChange) {
  14576. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14577. }
  14578. this._alphaMode = mode;
  14579. };
  14580. /**
  14581. * Gets the current alpha mode
  14582. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14583. * @returns the current alpha mode
  14584. */
  14585. Engine.prototype.getAlphaMode = function () {
  14586. return this._alphaMode;
  14587. };
  14588. // Textures
  14589. /**
  14590. * Clears the list of texture accessible through engine.
  14591. * This can help preventing texture load conflict due to name collision.
  14592. */
  14593. Engine.prototype.clearInternalTexturesCache = function () {
  14594. this._internalTexturesCache = [];
  14595. };
  14596. /**
  14597. * Force the entire cache to be cleared
  14598. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14599. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14600. */
  14601. Engine.prototype.wipeCaches = function (bruteForce) {
  14602. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14603. return;
  14604. }
  14605. this._currentEffect = null;
  14606. this._unpackFlipYCached = null;
  14607. this._viewportCached.x = 0;
  14608. this._viewportCached.y = 0;
  14609. this._viewportCached.z = 0;
  14610. this._viewportCached.w = 0;
  14611. if (bruteForce) {
  14612. this.resetTextureCache();
  14613. this._currentProgram = null;
  14614. this._stencilState.reset();
  14615. this._depthCullingState.reset();
  14616. this.setDepthFunctionToLessOrEqual();
  14617. this._alphaState.reset();
  14618. }
  14619. this._resetVertexBufferBinding();
  14620. this._cachedIndexBuffer = null;
  14621. this._cachedEffectForVertexBuffers = null;
  14622. this._unbindVertexArrayObject();
  14623. this.bindIndexBuffer(null);
  14624. };
  14625. /**
  14626. * Set the compressed texture format to use, based on the formats you have, and the formats
  14627. * supported by the hardware / browser.
  14628. *
  14629. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14630. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14631. * to API arguments needed to compressed textures. This puts the burden on the container
  14632. * generator to house the arcane code for determining these for current & future formats.
  14633. *
  14634. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14635. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14636. *
  14637. * Note: The result of this call is not taken into account when a texture is base64.
  14638. *
  14639. * @param formatsAvailable defines the list of those format families you have created
  14640. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14641. *
  14642. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14643. * @returns The extension selected.
  14644. */
  14645. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14646. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14647. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14648. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14649. return this._textureFormatInUse = this._texturesSupported[i];
  14650. }
  14651. }
  14652. }
  14653. // actively set format to nothing, to allow this to be called more than once
  14654. // and possibly fail the 2nd time
  14655. this._textureFormatInUse = null;
  14656. return null;
  14657. };
  14658. /** @hidden */
  14659. Engine.prototype._createTexture = function () {
  14660. var texture = this._gl.createTexture();
  14661. if (!texture) {
  14662. throw new Error("Unable to create texture");
  14663. }
  14664. return texture;
  14665. };
  14666. /**
  14667. * Usually called from BABYLON.Texture.ts.
  14668. * Passed information to create a WebGLTexture
  14669. * @param urlArg defines a value which contains one of the following:
  14670. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14671. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14672. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14673. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14674. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14675. * @param scene needed for loading to the correct scene
  14676. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14677. * @param onLoad optional callback to be called upon successful completion
  14678. * @param onError optional callback to be called upon failure
  14679. * @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
  14680. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14681. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14682. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14683. */
  14684. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14685. var _this = this;
  14686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14687. if (onLoad === void 0) { onLoad = null; }
  14688. if (onError === void 0) { onError = null; }
  14689. if (buffer === void 0) { buffer = null; }
  14690. if (fallback === void 0) { fallback = null; }
  14691. if (format === void 0) { format = null; }
  14692. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14693. var fromData = url.substr(0, 5) === "data:";
  14694. var fromBlob = url.substr(0, 5) === "blob:";
  14695. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14696. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14697. // establish the file extension, if possible
  14698. var lastDot = url.lastIndexOf('.');
  14699. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14700. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14701. var isTGA = (extension.indexOf(".tga") === 0);
  14702. // determine if a ktx file should be substituted
  14703. var isKTX = false;
  14704. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14705. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14706. isKTX = true;
  14707. }
  14708. if (scene) {
  14709. scene._addPendingData(texture);
  14710. }
  14711. texture.url = url;
  14712. texture.generateMipMaps = !noMipmap;
  14713. texture.samplingMode = samplingMode;
  14714. texture.invertY = invertY;
  14715. if (!this._doNotHandleContextLost) {
  14716. // Keep a link to the buffer only if we plan to handle context lost
  14717. texture._buffer = buffer;
  14718. }
  14719. var onLoadObserver = null;
  14720. if (onLoad && !fallback) {
  14721. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14722. }
  14723. if (!fallback)
  14724. this._internalTexturesCache.push(texture);
  14725. var onerror = function (message, exception) {
  14726. if (scene) {
  14727. scene._removePendingData(texture);
  14728. }
  14729. if (onLoadObserver && !isKTX) {
  14730. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14731. texture.onLoadedObservable.remove(onLoadObserver);
  14732. }
  14733. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14734. if (isKTX) {
  14735. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14736. }
  14737. else if (BABYLON.Tools.UseFallbackTexture) {
  14738. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14739. }
  14740. if (onError) {
  14741. onError(message || "Unknown error", exception);
  14742. }
  14743. };
  14744. var callback = null;
  14745. // processing for non-image formats
  14746. if (isKTX || isTGA || isDDS) {
  14747. if (isKTX) {
  14748. callback = function (data) {
  14749. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14750. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14751. ktx.uploadLevels(_this._gl, !noMipmap);
  14752. return false;
  14753. }, samplingMode);
  14754. };
  14755. }
  14756. else if (isTGA) {
  14757. callback = function (arrayBuffer) {
  14758. var data = new Uint8Array(arrayBuffer);
  14759. var header = BABYLON.TGATools.GetTGAHeader(data);
  14760. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14761. BABYLON.TGATools.UploadContent(_this._gl, data);
  14762. return false;
  14763. }, samplingMode);
  14764. };
  14765. }
  14766. else if (isDDS) {
  14767. callback = function (data) {
  14768. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14769. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14770. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14771. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14772. return false;
  14773. }, samplingMode);
  14774. };
  14775. }
  14776. if (!buffer) {
  14777. this._loadFile(url, function (data) {
  14778. if (callback) {
  14779. callback(data);
  14780. }
  14781. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14782. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14783. });
  14784. }
  14785. else {
  14786. if (callback) {
  14787. callback(buffer);
  14788. }
  14789. }
  14790. // image format processing
  14791. }
  14792. else {
  14793. var onload = function (img) {
  14794. if (fromBlob && !_this._doNotHandleContextLost) {
  14795. // We need to store the image if we need to rebuild the texture
  14796. // in case of a webgl context lost
  14797. texture._buffer = img;
  14798. }
  14799. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14800. var gl = _this._gl;
  14801. var isPot = (img.width === potWidth && img.height === potHeight);
  14802. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14803. if (isPot) {
  14804. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14805. return false;
  14806. }
  14807. var maxTextureSize = _this._caps.maxTextureSize;
  14808. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14809. _this._prepareWorkingCanvas();
  14810. if (!_this._workingCanvas || !_this._workingContext) {
  14811. return false;
  14812. }
  14813. _this._workingCanvas.width = potWidth;
  14814. _this._workingCanvas.height = potHeight;
  14815. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14816. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14817. texture.width = potWidth;
  14818. texture.height = potHeight;
  14819. return false;
  14820. }
  14821. else {
  14822. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14823. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14824. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14825. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14826. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14827. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14828. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14829. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14830. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14831. _this._releaseTexture(source_1);
  14832. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14833. continuationCallback();
  14834. });
  14835. }
  14836. return true;
  14837. }, samplingMode);
  14838. };
  14839. if (!fromData || isBase64) {
  14840. if (buffer instanceof HTMLImageElement) {
  14841. onload(buffer);
  14842. }
  14843. else {
  14844. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14845. }
  14846. }
  14847. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14848. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14849. }
  14850. else {
  14851. onload(buffer);
  14852. }
  14853. }
  14854. return texture;
  14855. };
  14856. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14857. var _this = this;
  14858. var rtt = this.createRenderTargetTexture({
  14859. width: destination.width,
  14860. height: destination.height,
  14861. }, {
  14862. generateMipMaps: false,
  14863. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14864. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14865. generateDepthBuffer: false,
  14866. generateStencilBuffer: false
  14867. });
  14868. if (!this._rescalePostProcess) {
  14869. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14870. }
  14871. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14872. _this._rescalePostProcess.onApply = function (effect) {
  14873. effect._bindTexture("textureSampler", source);
  14874. };
  14875. var hostingScene = scene;
  14876. if (!hostingScene) {
  14877. hostingScene = _this.scenes[_this.scenes.length - 1];
  14878. }
  14879. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14880. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14881. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14882. _this.unBindFramebuffer(rtt);
  14883. _this._releaseTexture(rtt);
  14884. if (onComplete) {
  14885. onComplete();
  14886. }
  14887. });
  14888. };
  14889. /**
  14890. * Update a raw texture
  14891. * @param texture defines the texture to update
  14892. * @param data defines the data to store in the texture
  14893. * @param format defines the format of the data
  14894. * @param invertY defines if data must be stored with Y axis inverted
  14895. * @param compression defines the compression used (null by default)
  14896. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14897. */
  14898. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14899. if (compression === void 0) { compression = null; }
  14900. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14901. if (!texture) {
  14902. return;
  14903. }
  14904. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14905. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14906. // babylon's internalFormat but gl's texImage2D format
  14907. var internalFormat = this._getInternalFormat(format);
  14908. var textureType = this._getWebGLTextureType(type);
  14909. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14910. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14911. if (!this._doNotHandleContextLost) {
  14912. texture._bufferView = data;
  14913. texture.format = format;
  14914. texture.type = type;
  14915. texture.invertY = invertY;
  14916. texture._compression = compression;
  14917. }
  14918. if (texture.width % 4 !== 0) {
  14919. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14920. }
  14921. if (compression && data) {
  14922. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14923. }
  14924. else {
  14925. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14926. }
  14927. if (texture.generateMipMaps) {
  14928. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14929. }
  14930. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14931. // this.resetTextureCache();
  14932. texture.isReady = true;
  14933. };
  14934. /**
  14935. * Creates a raw texture
  14936. * @param data defines the data to store in the texture
  14937. * @param width defines the width of the texture
  14938. * @param height defines the height of the texture
  14939. * @param format defines the format of the data
  14940. * @param generateMipMaps defines if the engine should generate the mip levels
  14941. * @param invertY defines if data must be stored with Y axis inverted
  14942. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14943. * @param compression defines the compression used (null by default)
  14944. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14945. * @returns the raw texture inside an InternalTexture
  14946. */
  14947. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14948. if (compression === void 0) { compression = null; }
  14949. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14950. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14951. texture.baseWidth = width;
  14952. texture.baseHeight = height;
  14953. texture.width = width;
  14954. texture.height = height;
  14955. texture.format = format;
  14956. texture.generateMipMaps = generateMipMaps;
  14957. texture.samplingMode = samplingMode;
  14958. texture.invertY = invertY;
  14959. texture._compression = compression;
  14960. texture.type = type;
  14961. if (!this._doNotHandleContextLost) {
  14962. texture._bufferView = data;
  14963. }
  14964. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14965. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14966. // Filters
  14967. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14968. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14969. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14970. if (generateMipMaps) {
  14971. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14972. }
  14973. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14974. this._internalTexturesCache.push(texture);
  14975. return texture;
  14976. };
  14977. /** @hidden */
  14978. Engine.prototype._unpackFlipY = function (value) {
  14979. if (this._unpackFlipYCached !== value) {
  14980. this._unpackFlipYCached = value;
  14981. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14982. }
  14983. };
  14984. /**
  14985. * Creates a dynamic texture
  14986. * @param width defines the width of the texture
  14987. * @param height defines the height of the texture
  14988. * @param generateMipMaps defines if the engine should generate the mip levels
  14989. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14990. * @returns the dynamic texture inside an InternalTexture
  14991. */
  14992. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14993. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14994. texture.baseWidth = width;
  14995. texture.baseHeight = height;
  14996. if (generateMipMaps) {
  14997. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14998. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14999. }
  15000. // this.resetTextureCache();
  15001. texture.width = width;
  15002. texture.height = height;
  15003. texture.isReady = false;
  15004. texture.generateMipMaps = generateMipMaps;
  15005. texture.samplingMode = samplingMode;
  15006. this.updateTextureSamplingMode(samplingMode, texture);
  15007. this._internalTexturesCache.push(texture);
  15008. return texture;
  15009. };
  15010. /**
  15011. * Update the sampling mode of a given texture
  15012. * @param samplingMode defines the required sampling mode
  15013. * @param texture defines the texture to update
  15014. */
  15015. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15016. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  15017. if (texture.isCube) {
  15018. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15019. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15020. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15021. }
  15022. else if (texture.is3D) {
  15023. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15024. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15025. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15026. }
  15027. else {
  15028. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15029. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15030. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15031. }
  15032. texture.samplingMode = samplingMode;
  15033. };
  15034. /**
  15035. * Update the content of a dynamic texture
  15036. * @param texture defines the texture to update
  15037. * @param canvas defines the canvas containing the source
  15038. * @param invertY defines if data must be stored with Y axis inverted
  15039. * @param premulAlpha defines if alpha is stored as premultiplied
  15040. * @param format defines the format of the data
  15041. */
  15042. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15043. if (premulAlpha === void 0) { premulAlpha = false; }
  15044. if (!texture) {
  15045. return;
  15046. }
  15047. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15048. this._unpackFlipY(invertY);
  15049. if (premulAlpha) {
  15050. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15051. }
  15052. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15053. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15054. if (texture.generateMipMaps) {
  15055. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15056. }
  15057. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15058. if (premulAlpha) {
  15059. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15060. }
  15061. texture.isReady = true;
  15062. };
  15063. /**
  15064. * Update a video texture
  15065. * @param texture defines the texture to update
  15066. * @param video defines the video element to use
  15067. * @param invertY defines if data must be stored with Y axis inverted
  15068. */
  15069. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15070. if (!texture || texture._isDisabled) {
  15071. return;
  15072. }
  15073. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15074. this._unpackFlipY(!invertY); // Video are upside down by default
  15075. try {
  15076. // Testing video texture support
  15077. if (this._videoTextureSupported === undefined) {
  15078. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15079. if (this._gl.getError() !== 0) {
  15080. this._videoTextureSupported = false;
  15081. }
  15082. else {
  15083. this._videoTextureSupported = true;
  15084. }
  15085. }
  15086. // Copy video through the current working canvas if video texture is not supported
  15087. if (!this._videoTextureSupported) {
  15088. if (!texture._workingCanvas) {
  15089. texture._workingCanvas = document.createElement("canvas");
  15090. var context = texture._workingCanvas.getContext("2d");
  15091. if (!context) {
  15092. throw new Error("Unable to get 2d context");
  15093. }
  15094. texture._workingContext = context;
  15095. texture._workingCanvas.width = texture.width;
  15096. texture._workingCanvas.height = texture.height;
  15097. }
  15098. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15099. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15100. }
  15101. else {
  15102. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15103. }
  15104. if (texture.generateMipMaps) {
  15105. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15106. }
  15107. if (!wasPreviouslyBound) {
  15108. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15109. }
  15110. // this.resetTextureCache();
  15111. texture.isReady = true;
  15112. }
  15113. catch (ex) {
  15114. // Something unexpected
  15115. // Let's disable the texture
  15116. texture._isDisabled = true;
  15117. }
  15118. };
  15119. /**
  15120. * Updates a depth texture Comparison Mode and Function.
  15121. * If the comparison Function is equal to 0, the mode will be set to none.
  15122. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15123. * @param texture The texture to set the comparison function for
  15124. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15125. */
  15126. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15127. if (this.webGLVersion === 1) {
  15128. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15129. return;
  15130. }
  15131. var gl = this._gl;
  15132. if (texture.isCube) {
  15133. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15134. if (comparisonFunction === 0) {
  15135. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15137. }
  15138. else {
  15139. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15140. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15141. }
  15142. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15143. }
  15144. else {
  15145. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15146. if (comparisonFunction === 0) {
  15147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15148. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15149. }
  15150. else {
  15151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15153. }
  15154. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15155. }
  15156. texture._comparisonFunction = comparisonFunction;
  15157. };
  15158. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15159. var width = size.width || size;
  15160. var height = size.height || size;
  15161. internalTexture.baseWidth = width;
  15162. internalTexture.baseHeight = height;
  15163. internalTexture.width = width;
  15164. internalTexture.height = height;
  15165. internalTexture.isReady = true;
  15166. internalTexture.samples = 1;
  15167. internalTexture.generateMipMaps = false;
  15168. internalTexture._generateDepthBuffer = true;
  15169. internalTexture._generateStencilBuffer = generateStencil;
  15170. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15171. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15172. internalTexture._comparisonFunction = comparisonFunction;
  15173. var gl = this._gl;
  15174. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15175. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15176. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15177. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15178. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15179. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15180. if (comparisonFunction === 0) {
  15181. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15182. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15183. }
  15184. else {
  15185. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15186. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15187. }
  15188. };
  15189. /**
  15190. * Creates a depth stencil texture.
  15191. * This is only available in WebGL 2 or with the depth texture extension available.
  15192. * @param size The size of face edge in the texture.
  15193. * @param options The options defining the texture.
  15194. * @returns The texture
  15195. */
  15196. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15197. if (options.isCube) {
  15198. var width = size.width || size;
  15199. return this._createDepthStencilCubeTexture(width, options);
  15200. }
  15201. else {
  15202. return this._createDepthStencilTexture(size, options);
  15203. }
  15204. };
  15205. /**
  15206. * Creates a depth stencil texture.
  15207. * This is only available in WebGL 2 or with the depth texture extension available.
  15208. * @param size The size of face edge in the texture.
  15209. * @param options The options defining the texture.
  15210. * @returns The texture
  15211. */
  15212. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15213. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15214. if (!this._caps.depthTextureExtension) {
  15215. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15216. return internalTexture;
  15217. }
  15218. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15219. var gl = this._gl;
  15220. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15221. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15222. if (this.webGLVersion > 1) {
  15223. if (internalOptions.generateStencil) {
  15224. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15225. }
  15226. else {
  15227. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15228. }
  15229. }
  15230. else {
  15231. if (internalOptions.generateStencil) {
  15232. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15233. }
  15234. else {
  15235. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15236. }
  15237. }
  15238. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15239. return internalTexture;
  15240. };
  15241. /**
  15242. * Creates a depth stencil cube texture.
  15243. * This is only available in WebGL 2.
  15244. * @param size The size of face edge in the cube texture.
  15245. * @param options The options defining the cube texture.
  15246. * @returns The cube texture
  15247. */
  15248. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15249. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15250. internalTexture.isCube = true;
  15251. if (this.webGLVersion === 1) {
  15252. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15253. return internalTexture;
  15254. }
  15255. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15256. var gl = this._gl;
  15257. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15258. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15259. // Create the depth/stencil buffer
  15260. for (var face = 0; face < 6; face++) {
  15261. if (internalOptions.generateStencil) {
  15262. 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);
  15263. }
  15264. else {
  15265. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15266. }
  15267. }
  15268. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15269. return internalTexture;
  15270. };
  15271. /**
  15272. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15273. * @param renderTarget The render target to set the frame buffer for
  15274. */
  15275. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15276. // Create the framebuffer
  15277. var internalTexture = renderTarget.getInternalTexture();
  15278. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15279. return;
  15280. }
  15281. var gl = this._gl;
  15282. var depthStencilTexture = renderTarget.depthStencilTexture;
  15283. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15284. if (depthStencilTexture.isCube) {
  15285. if (depthStencilTexture._generateStencilBuffer) {
  15286. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15287. }
  15288. else {
  15289. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15290. }
  15291. }
  15292. else {
  15293. if (depthStencilTexture._generateStencilBuffer) {
  15294. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15295. }
  15296. else {
  15297. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15298. }
  15299. }
  15300. this.bindUnboundFramebuffer(null);
  15301. };
  15302. /**
  15303. * Creates a new render target texture
  15304. * @param size defines the size of the texture
  15305. * @param options defines the options used to create the texture
  15306. * @returns a new render target texture stored in an InternalTexture
  15307. */
  15308. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15309. var fullOptions = new RenderTargetCreationOptions();
  15310. if (options !== undefined && typeof options === "object") {
  15311. fullOptions.generateMipMaps = options.generateMipMaps;
  15312. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15313. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15314. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15315. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15316. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15317. }
  15318. else {
  15319. fullOptions.generateMipMaps = options;
  15320. fullOptions.generateDepthBuffer = true;
  15321. fullOptions.generateStencilBuffer = false;
  15322. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15323. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15324. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15325. }
  15326. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15327. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15328. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15329. }
  15330. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15331. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15332. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15333. }
  15334. var gl = this._gl;
  15335. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15336. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15337. var width = size.width || size;
  15338. var height = size.height || size;
  15339. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15340. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15341. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15342. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15343. }
  15344. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15347. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15348. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15349. // Create the framebuffer
  15350. var currentFrameBuffer = this._currentFramebuffer;
  15351. var framebuffer = gl.createFramebuffer();
  15352. this.bindUnboundFramebuffer(framebuffer);
  15353. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15354. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15355. if (fullOptions.generateMipMaps) {
  15356. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15357. }
  15358. // Unbind
  15359. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15360. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15361. this.bindUnboundFramebuffer(currentFrameBuffer);
  15362. texture._framebuffer = framebuffer;
  15363. texture.baseWidth = width;
  15364. texture.baseHeight = height;
  15365. texture.width = width;
  15366. texture.height = height;
  15367. texture.isReady = true;
  15368. texture.samples = 1;
  15369. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15370. texture.samplingMode = fullOptions.samplingMode;
  15371. texture.type = fullOptions.type;
  15372. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15373. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15374. // this.resetTextureCache();
  15375. this._internalTexturesCache.push(texture);
  15376. return texture;
  15377. };
  15378. /**
  15379. * Create a multi render target texture
  15380. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15381. * @param size defines the size of the texture
  15382. * @param options defines the creation options
  15383. * @returns the cube texture as an InternalTexture
  15384. */
  15385. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15386. var generateMipMaps = false;
  15387. var generateDepthBuffer = true;
  15388. var generateStencilBuffer = false;
  15389. var generateDepthTexture = false;
  15390. var textureCount = 1;
  15391. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15392. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15393. var types = new Array();
  15394. var samplingModes = new Array();
  15395. if (options !== undefined) {
  15396. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15397. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15398. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15399. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15400. textureCount = options.textureCount || 1;
  15401. if (options.types) {
  15402. types = options.types;
  15403. }
  15404. if (options.samplingModes) {
  15405. samplingModes = options.samplingModes;
  15406. }
  15407. }
  15408. var gl = this._gl;
  15409. // Create the framebuffer
  15410. var framebuffer = gl.createFramebuffer();
  15411. this.bindUnboundFramebuffer(framebuffer);
  15412. var width = size.width || size;
  15413. var height = size.height || size;
  15414. var textures = [];
  15415. var attachments = [];
  15416. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15417. for (var i = 0; i < textureCount; i++) {
  15418. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15419. var type = types[i] || defaultType;
  15420. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15421. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15422. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15423. }
  15424. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15425. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15426. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15427. }
  15428. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15429. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15430. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15431. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15432. }
  15433. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15434. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15435. textures.push(texture);
  15436. attachments.push(attachment);
  15437. gl.activeTexture(gl["TEXTURE" + i]);
  15438. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15440. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15441. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15442. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15443. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15444. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15445. if (generateMipMaps) {
  15446. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15447. }
  15448. // Unbind
  15449. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15450. texture._framebuffer = framebuffer;
  15451. texture._depthStencilBuffer = depthStencilBuffer;
  15452. texture.baseWidth = width;
  15453. texture.baseHeight = height;
  15454. texture.width = width;
  15455. texture.height = height;
  15456. texture.isReady = true;
  15457. texture.samples = 1;
  15458. texture.generateMipMaps = generateMipMaps;
  15459. texture.samplingMode = samplingMode;
  15460. texture.type = type;
  15461. texture._generateDepthBuffer = generateDepthBuffer;
  15462. texture._generateStencilBuffer = generateStencilBuffer;
  15463. texture._attachments = attachments;
  15464. this._internalTexturesCache.push(texture);
  15465. }
  15466. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15467. // Depth texture
  15468. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15469. gl.activeTexture(gl.TEXTURE0);
  15470. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15471. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15472. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15473. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15474. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15475. 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);
  15476. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15477. depthTexture._framebuffer = framebuffer;
  15478. depthTexture.baseWidth = width;
  15479. depthTexture.baseHeight = height;
  15480. depthTexture.width = width;
  15481. depthTexture.height = height;
  15482. depthTexture.isReady = true;
  15483. depthTexture.samples = 1;
  15484. depthTexture.generateMipMaps = generateMipMaps;
  15485. depthTexture.samplingMode = gl.NEAREST;
  15486. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15487. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15488. textures.push(depthTexture);
  15489. this._internalTexturesCache.push(depthTexture);
  15490. }
  15491. gl.drawBuffers(attachments);
  15492. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15493. this.bindUnboundFramebuffer(null);
  15494. this.resetTextureCache();
  15495. return textures;
  15496. };
  15497. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15498. if (samples === void 0) { samples = 1; }
  15499. var depthStencilBuffer = null;
  15500. var gl = this._gl;
  15501. // Create the depth/stencil buffer
  15502. if (generateStencilBuffer) {
  15503. depthStencilBuffer = gl.createRenderbuffer();
  15504. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15505. if (samples > 1) {
  15506. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15507. }
  15508. else {
  15509. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15510. }
  15511. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15512. }
  15513. else if (generateDepthBuffer) {
  15514. depthStencilBuffer = gl.createRenderbuffer();
  15515. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15516. if (samples > 1) {
  15517. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15518. }
  15519. else {
  15520. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15521. }
  15522. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15523. }
  15524. return depthStencilBuffer;
  15525. };
  15526. /**
  15527. * Updates the sample count of a render target texture
  15528. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15529. * @param texture defines the texture to update
  15530. * @param samples defines the sample count to set
  15531. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15532. */
  15533. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15534. if (this.webGLVersion < 2 || !texture) {
  15535. return 1;
  15536. }
  15537. if (texture.samples === samples) {
  15538. return samples;
  15539. }
  15540. var gl = this._gl;
  15541. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15542. // Dispose previous render buffers
  15543. if (texture._depthStencilBuffer) {
  15544. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15545. texture._depthStencilBuffer = null;
  15546. }
  15547. if (texture._MSAAFramebuffer) {
  15548. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15549. texture._MSAAFramebuffer = null;
  15550. }
  15551. if (texture._MSAARenderBuffer) {
  15552. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15553. texture._MSAARenderBuffer = null;
  15554. }
  15555. if (samples > 1) {
  15556. var framebuffer = gl.createFramebuffer();
  15557. if (!framebuffer) {
  15558. throw new Error("Unable to create multi sampled framebuffer");
  15559. }
  15560. texture._MSAAFramebuffer = framebuffer;
  15561. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15562. var colorRenderbuffer = gl.createRenderbuffer();
  15563. if (!colorRenderbuffer) {
  15564. throw new Error("Unable to create multi sampled framebuffer");
  15565. }
  15566. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15567. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15568. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15569. texture._MSAARenderBuffer = colorRenderbuffer;
  15570. }
  15571. else {
  15572. this.bindUnboundFramebuffer(texture._framebuffer);
  15573. }
  15574. texture.samples = samples;
  15575. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15576. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15577. this.bindUnboundFramebuffer(null);
  15578. return samples;
  15579. };
  15580. /**
  15581. * Update the sample count for a given multiple render target texture
  15582. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15583. * @param textures defines the textures to update
  15584. * @param samples defines the sample count to set
  15585. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15586. */
  15587. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15588. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15589. return 1;
  15590. }
  15591. if (textures[0].samples === samples) {
  15592. return samples;
  15593. }
  15594. var gl = this._gl;
  15595. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15596. // Dispose previous render buffers
  15597. if (textures[0]._depthStencilBuffer) {
  15598. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15599. textures[0]._depthStencilBuffer = null;
  15600. }
  15601. if (textures[0]._MSAAFramebuffer) {
  15602. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15603. textures[0]._MSAAFramebuffer = null;
  15604. }
  15605. for (var i = 0; i < textures.length; i++) {
  15606. if (textures[i]._MSAARenderBuffer) {
  15607. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15608. textures[i]._MSAARenderBuffer = null;
  15609. }
  15610. }
  15611. if (samples > 1) {
  15612. var framebuffer = gl.createFramebuffer();
  15613. if (!framebuffer) {
  15614. throw new Error("Unable to create multi sampled framebuffer");
  15615. }
  15616. this.bindUnboundFramebuffer(framebuffer);
  15617. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15618. var attachments = [];
  15619. for (var i = 0; i < textures.length; i++) {
  15620. var texture = textures[i];
  15621. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15622. var colorRenderbuffer = gl.createRenderbuffer();
  15623. if (!colorRenderbuffer) {
  15624. throw new Error("Unable to create multi sampled framebuffer");
  15625. }
  15626. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15627. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15628. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15629. texture._MSAAFramebuffer = framebuffer;
  15630. texture._MSAARenderBuffer = colorRenderbuffer;
  15631. texture.samples = samples;
  15632. texture._depthStencilBuffer = depthStencilBuffer;
  15633. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15634. attachments.push(attachment);
  15635. }
  15636. gl.drawBuffers(attachments);
  15637. }
  15638. else {
  15639. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15640. }
  15641. this.bindUnboundFramebuffer(null);
  15642. return samples;
  15643. };
  15644. /** @hidden */
  15645. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15646. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15647. };
  15648. /** @hidden */
  15649. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15650. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15651. };
  15652. /** @hidden */
  15653. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15654. var gl = this._gl;
  15655. var textureType = this._getWebGLTextureType(texture.type);
  15656. var format = this._getInternalFormat(texture.format);
  15657. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15658. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15659. this._bindTextureDirectly(bindTarget, texture, true);
  15660. this._unpackFlipY(texture.invertY);
  15661. var target = gl.TEXTURE_2D;
  15662. if (texture.isCube) {
  15663. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15664. }
  15665. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15666. this._bindTextureDirectly(bindTarget, null, true);
  15667. };
  15668. /**
  15669. * Creates a new render target cube texture
  15670. * @param size defines the size of the texture
  15671. * @param options defines the options used to create the texture
  15672. * @returns a new render target cube texture stored in an InternalTexture
  15673. */
  15674. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15675. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15676. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15677. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15678. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15679. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15680. }
  15681. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15682. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15683. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15684. }
  15685. var gl = this._gl;
  15686. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15687. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15688. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15689. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15690. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15691. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15692. }
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15697. for (var face = 0; face < 6; face++) {
  15698. 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);
  15699. }
  15700. // Create the framebuffer
  15701. var framebuffer = gl.createFramebuffer();
  15702. this.bindUnboundFramebuffer(framebuffer);
  15703. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15704. // MipMaps
  15705. if (fullOptions.generateMipMaps) {
  15706. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15707. }
  15708. // Unbind
  15709. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15710. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15711. this.bindUnboundFramebuffer(null);
  15712. texture._framebuffer = framebuffer;
  15713. texture.width = size;
  15714. texture.height = size;
  15715. texture.isReady = true;
  15716. texture.isCube = true;
  15717. texture.samples = 1;
  15718. texture.generateMipMaps = fullOptions.generateMipMaps;
  15719. texture.samplingMode = fullOptions.samplingMode;
  15720. texture.type = fullOptions.type;
  15721. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15722. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15723. this._internalTexturesCache.push(texture);
  15724. return texture;
  15725. };
  15726. /**
  15727. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15728. * @param rootUrl defines the url where the file to load is located
  15729. * @param scene defines the current scene
  15730. * @param lodScale defines scale to apply to the mip map selection
  15731. * @param lodOffset defines offset to apply to the mip map selection
  15732. * @param onLoad defines an optional callback raised when the texture is loaded
  15733. * @param onError defines an optional callback raised if there is an issue to load the texture
  15734. * @param format defines the format of the data
  15735. * @param forcedExtension defines the extension to use to pick the right loader
  15736. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15737. * @returns the cube texture as an InternalTexture
  15738. */
  15739. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15740. var _this = this;
  15741. if (onLoad === void 0) { onLoad = null; }
  15742. if (onError === void 0) { onError = null; }
  15743. if (forcedExtension === void 0) { forcedExtension = null; }
  15744. if (createPolynomials === void 0) { createPolynomials = true; }
  15745. var callback = function (loadData) {
  15746. if (!loadData) {
  15747. if (onLoad) {
  15748. onLoad(null);
  15749. }
  15750. return;
  15751. }
  15752. var texture = loadData.texture;
  15753. if (!createPolynomials) {
  15754. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15755. }
  15756. else if (loadData.info.sphericalPolynomial) {
  15757. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15758. }
  15759. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15760. if (_this._caps.textureLOD) {
  15761. // Do not add extra process if texture lod is supported.
  15762. if (onLoad) {
  15763. onLoad(texture);
  15764. }
  15765. return;
  15766. }
  15767. var mipSlices = 3;
  15768. var gl = _this._gl;
  15769. var width = loadData.width;
  15770. if (!width) {
  15771. return;
  15772. }
  15773. var textures = [];
  15774. for (var i = 0; i < mipSlices; i++) {
  15775. //compute LOD from even spacing in smoothness (matching shader calculation)
  15776. var smoothness = i / (mipSlices - 1);
  15777. var roughness = 1 - smoothness;
  15778. var minLODIndex = lodOffset; // roughness = 0
  15779. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15780. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15781. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15782. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15783. glTextureFromLod.isCube = true;
  15784. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15789. if (loadData.isDDS) {
  15790. var info = loadData.info;
  15791. var data = loadData.data;
  15792. _this._unpackFlipY(info.isCompressed);
  15793. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15794. }
  15795. else {
  15796. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15797. }
  15798. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15799. // Wrap in a base texture for easy binding.
  15800. var lodTexture = new BABYLON.BaseTexture(scene);
  15801. lodTexture.isCube = true;
  15802. lodTexture._texture = glTextureFromLod;
  15803. glTextureFromLod.isReady = true;
  15804. textures.push(lodTexture);
  15805. }
  15806. texture._lodTextureHigh = textures[2];
  15807. texture._lodTextureMid = textures[1];
  15808. texture._lodTextureLow = textures[0];
  15809. if (onLoad) {
  15810. onLoad(texture);
  15811. }
  15812. };
  15813. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15814. };
  15815. /**
  15816. * Creates a cube texture
  15817. * @param rootUrl defines the url where the files to load is located
  15818. * @param scene defines the current scene
  15819. * @param files defines the list of files to load (1 per face)
  15820. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15821. * @param onLoad defines an optional callback raised when the texture is loaded
  15822. * @param onError defines an optional callback raised if there is an issue to load the texture
  15823. * @param format defines the format of the data
  15824. * @param forcedExtension defines the extension to use to pick the right loader
  15825. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15826. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15827. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15828. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15829. * @returns the cube texture as an InternalTexture
  15830. */
  15831. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15832. var _this = this;
  15833. if (onLoad === void 0) { onLoad = null; }
  15834. if (onError === void 0) { onError = null; }
  15835. if (forcedExtension === void 0) { forcedExtension = null; }
  15836. if (createPolynomials === void 0) { createPolynomials = false; }
  15837. if (lodScale === void 0) { lodScale = 0; }
  15838. if (lodOffset === void 0) { lodOffset = 0; }
  15839. if (fallback === void 0) { fallback = null; }
  15840. var gl = this._gl;
  15841. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15842. texture.isCube = true;
  15843. texture.url = rootUrl;
  15844. texture.generateMipMaps = !noMipmap;
  15845. texture._lodGenerationScale = lodScale;
  15846. texture._lodGenerationOffset = lodOffset;
  15847. if (!this._doNotHandleContextLost) {
  15848. texture._extension = forcedExtension;
  15849. texture._files = files;
  15850. }
  15851. var isKTX = false;
  15852. var isDDS = false;
  15853. var isEnv = false;
  15854. var lastDot = rootUrl.lastIndexOf('.');
  15855. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15856. if (this._textureFormatInUse && !fallback) {
  15857. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15858. isKTX = true;
  15859. }
  15860. else {
  15861. isDDS = (extension === ".dds");
  15862. isEnv = (extension === ".env");
  15863. }
  15864. var onerror = function (request, exception) {
  15865. if (isKTX) {
  15866. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15867. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15868. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15869. }
  15870. if (onError && request) {
  15871. onError(request.status + " " + request.statusText, exception);
  15872. }
  15873. };
  15874. if (isKTX) {
  15875. this._loadFile(rootUrl, function (data) {
  15876. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15877. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15878. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15879. _this._unpackFlipY(true);
  15880. ktx.uploadLevels(_this._gl, !noMipmap);
  15881. _this.setCubeMapTextureParams(gl, loadMipmap);
  15882. texture.width = ktx.pixelWidth;
  15883. texture.height = ktx.pixelHeight;
  15884. texture.isReady = true;
  15885. }, undefined, undefined, true, onerror);
  15886. }
  15887. else if (isEnv) {
  15888. this._loadFile(rootUrl, function (data) {
  15889. data = data;
  15890. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15891. if (info) {
  15892. texture.width = info.width;
  15893. texture.height = info.width;
  15894. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15895. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15896. texture.isReady = true;
  15897. if (onLoad) {
  15898. onLoad();
  15899. }
  15900. });
  15901. }
  15902. else if (onError) {
  15903. onError("Can not parse the environment file", null);
  15904. }
  15905. }, undefined, undefined, true, onerror);
  15906. }
  15907. else if (isDDS) {
  15908. if (files && files.length === 6) {
  15909. this._cascadeLoadFiles(scene, function (imgs) {
  15910. var info;
  15911. var loadMipmap = false;
  15912. var width = 0;
  15913. for (var index = 0; index < imgs.length; index++) {
  15914. var data = imgs[index];
  15915. info = BABYLON.DDSTools.GetDDSInfo(data);
  15916. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15917. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15918. _this._unpackFlipY(info.isCompressed);
  15919. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15920. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15921. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15922. }
  15923. texture.width = info.width;
  15924. texture.height = info.height;
  15925. texture.type = info.textureType;
  15926. width = info.width;
  15927. }
  15928. _this.setCubeMapTextureParams(gl, loadMipmap);
  15929. texture.isReady = true;
  15930. if (onLoad) {
  15931. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15932. }
  15933. }, files, onError);
  15934. }
  15935. else {
  15936. this._loadFile(rootUrl, function (data) {
  15937. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15938. if (createPolynomials) {
  15939. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15940. }
  15941. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15942. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15943. _this._unpackFlipY(info.isCompressed);
  15944. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15945. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15946. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15947. }
  15948. _this.setCubeMapTextureParams(gl, loadMipmap);
  15949. texture.width = info.width;
  15950. texture.height = info.height;
  15951. texture.isReady = true;
  15952. texture.type = info.textureType;
  15953. if (onLoad) {
  15954. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15955. }
  15956. }, undefined, undefined, true, onerror);
  15957. }
  15958. }
  15959. else {
  15960. if (!files) {
  15961. throw new Error("Cannot load cubemap because files were not defined");
  15962. }
  15963. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15964. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15965. var height = width;
  15966. _this._prepareWorkingCanvas();
  15967. if (!_this._workingCanvas || !_this._workingContext) {
  15968. return;
  15969. }
  15970. _this._workingCanvas.width = width;
  15971. _this._workingCanvas.height = height;
  15972. var faces = [
  15973. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15974. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15975. ];
  15976. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15977. _this._unpackFlipY(false);
  15978. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15979. for (var index = 0; index < faces.length; index++) {
  15980. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15981. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15982. }
  15983. if (!noMipmap) {
  15984. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15985. }
  15986. _this.setCubeMapTextureParams(gl, !noMipmap);
  15987. texture.width = width;
  15988. texture.height = height;
  15989. texture.isReady = true;
  15990. if (format) {
  15991. texture.format = format;
  15992. }
  15993. texture.onLoadedObservable.notifyObservers(texture);
  15994. texture.onLoadedObservable.clear();
  15995. if (onLoad) {
  15996. onLoad();
  15997. }
  15998. }, files, onError);
  15999. }
  16000. this._internalTexturesCache.push(texture);
  16001. return texture;
  16002. };
  16003. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  16004. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16005. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16006. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16008. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16009. // this.resetTextureCache();
  16010. };
  16011. /**
  16012. * Update a raw cube texture
  16013. * @param texture defines the texture to udpdate
  16014. * @param data defines the data to store
  16015. * @param format defines the data format
  16016. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16017. * @param invertY defines if data must be stored with Y axis inverted
  16018. * @param compression defines the compression used (null by default)
  16019. * @param level defines which level of the texture to update
  16020. */
  16021. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16022. if (compression === void 0) { compression = null; }
  16023. if (level === void 0) { level = 0; }
  16024. texture._bufferViewArray = data;
  16025. texture.format = format;
  16026. texture.type = type;
  16027. texture.invertY = invertY;
  16028. texture._compression = compression;
  16029. var gl = this._gl;
  16030. var textureType = this._getWebGLTextureType(type);
  16031. var internalFormat = this._getInternalFormat(format);
  16032. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16033. var needConversion = false;
  16034. if (internalFormat === gl.RGB) {
  16035. internalFormat = gl.RGBA;
  16036. needConversion = true;
  16037. }
  16038. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16039. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16040. if (texture.width % 4 !== 0) {
  16041. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16042. }
  16043. // Data are known to be in +X +Y +Z -X -Y -Z
  16044. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16045. var faceData = data[faceIndex];
  16046. if (compression) {
  16047. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16048. }
  16049. else {
  16050. if (needConversion) {
  16051. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16052. }
  16053. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16054. }
  16055. }
  16056. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16057. if (isPot && texture.generateMipMaps && level === 0) {
  16058. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16059. }
  16060. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16061. // this.resetTextureCache();
  16062. texture.isReady = true;
  16063. };
  16064. /**
  16065. * Creates a new raw cube texture
  16066. * @param data defines the array of data to use to create each face
  16067. * @param size defines the size of the textures
  16068. * @param format defines the format of the data
  16069. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16070. * @param generateMipMaps defines if the engine should generate the mip levels
  16071. * @param invertY defines if data must be stored with Y axis inverted
  16072. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16073. * @param compression defines the compression used (null by default)
  16074. * @returns the cube texture as an InternalTexture
  16075. */
  16076. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16077. if (compression === void 0) { compression = null; }
  16078. var gl = this._gl;
  16079. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16080. texture.isCube = true;
  16081. texture.generateMipMaps = generateMipMaps;
  16082. texture.format = format;
  16083. texture.type = type;
  16084. if (!this._doNotHandleContextLost) {
  16085. texture._bufferViewArray = data;
  16086. }
  16087. var textureType = this._getWebGLTextureType(type);
  16088. var internalFormat = this._getInternalFormat(format);
  16089. if (internalFormat === gl.RGB) {
  16090. internalFormat = gl.RGBA;
  16091. }
  16092. var width = size;
  16093. var height = width;
  16094. texture.width = width;
  16095. texture.height = height;
  16096. // Double check on POT to generate Mips.
  16097. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16098. if (!isPot) {
  16099. generateMipMaps = false;
  16100. }
  16101. // Upload data if needed. The texture won't be ready until then.
  16102. if (data) {
  16103. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16104. }
  16105. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16106. // Filters
  16107. if (data && generateMipMaps) {
  16108. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16109. }
  16110. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16113. }
  16114. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16116. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16117. }
  16118. else {
  16119. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16122. }
  16123. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16124. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16125. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16126. return texture;
  16127. };
  16128. /**
  16129. * Creates a new raw cube texture from a specified url
  16130. * @param url defines the url where the data is located
  16131. * @param scene defines the current scene
  16132. * @param size defines the size of the textures
  16133. * @param format defines the format of the data
  16134. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16135. * @param noMipmap defines if the engine should avoid generating the mip levels
  16136. * @param callback defines a callback used to extract texture data from loaded data
  16137. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16138. * @param onLoad defines a callback called when texture is loaded
  16139. * @param onError defines a callback called if there is an error
  16140. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16141. * @param invertY defines if data must be stored with Y axis inverted
  16142. * @returns the cube texture as an InternalTexture
  16143. */
  16144. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16145. var _this = this;
  16146. if (onLoad === void 0) { onLoad = null; }
  16147. if (onError === void 0) { onError = null; }
  16148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16149. if (invertY === void 0) { invertY = false; }
  16150. var gl = this._gl;
  16151. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16152. scene._addPendingData(texture);
  16153. texture.url = url;
  16154. this._internalTexturesCache.push(texture);
  16155. var onerror = function (request, exception) {
  16156. scene._removePendingData(texture);
  16157. if (onError && request) {
  16158. onError(request.status + " " + request.statusText, exception);
  16159. }
  16160. };
  16161. var internalCallback = function (data) {
  16162. var width = texture.width;
  16163. var faceDataArrays = callback(data);
  16164. if (!faceDataArrays) {
  16165. return;
  16166. }
  16167. if (mipmapGenerator) {
  16168. var textureType = _this._getWebGLTextureType(type);
  16169. var internalFormat = _this._getInternalFormat(format);
  16170. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16171. var needConversion = false;
  16172. if (internalFormat === gl.RGB) {
  16173. internalFormat = gl.RGBA;
  16174. needConversion = true;
  16175. }
  16176. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16177. _this._unpackFlipY(false);
  16178. var mipData = mipmapGenerator(faceDataArrays);
  16179. for (var level = 0; level < mipData.length; level++) {
  16180. var mipSize = width >> level;
  16181. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16182. var mipFaceData = mipData[level][faceIndex];
  16183. if (needConversion) {
  16184. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16185. }
  16186. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16187. }
  16188. }
  16189. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16190. }
  16191. else {
  16192. texture.generateMipMaps = !noMipmap;
  16193. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16194. }
  16195. texture.isReady = true;
  16196. // this.resetTextureCache();
  16197. scene._removePendingData(texture);
  16198. if (onLoad) {
  16199. onLoad();
  16200. }
  16201. };
  16202. this._loadFile(url, function (data) {
  16203. internalCallback(data);
  16204. }, undefined, scene.database, true, onerror);
  16205. return texture;
  16206. };
  16207. ;
  16208. /**
  16209. * Update a raw 3D texture
  16210. * @param texture defines the texture to update
  16211. * @param data defines the data to store
  16212. * @param format defines the data format
  16213. * @param invertY defines if data must be stored with Y axis inverted
  16214. * @param compression defines the used compression (can be null)
  16215. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16216. */
  16217. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16218. if (compression === void 0) { compression = null; }
  16219. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16220. var internalType = this._getWebGLTextureType(textureType);
  16221. var internalFormat = this._getInternalFormat(format);
  16222. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16223. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16224. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16225. if (!this._doNotHandleContextLost) {
  16226. texture._bufferView = data;
  16227. texture.format = format;
  16228. texture.invertY = invertY;
  16229. texture._compression = compression;
  16230. }
  16231. if (texture.width % 4 !== 0) {
  16232. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16233. }
  16234. if (compression && data) {
  16235. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16236. }
  16237. else {
  16238. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16239. }
  16240. if (texture.generateMipMaps) {
  16241. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16242. }
  16243. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16244. // this.resetTextureCache();
  16245. texture.isReady = true;
  16246. };
  16247. /**
  16248. * Creates a new raw 3D texture
  16249. * @param data defines the data used to create the texture
  16250. * @param width defines the width of the texture
  16251. * @param height defines the height of the texture
  16252. * @param depth defines the depth of the texture
  16253. * @param format defines the format of the texture
  16254. * @param generateMipMaps defines if the engine must generate mip levels
  16255. * @param invertY defines if data must be stored with Y axis inverted
  16256. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16257. * @param compression defines the compressed used (can be null)
  16258. * @param textureType defines the compressed used (can be null)
  16259. * @returns a new raw 3D texture (stored in an InternalTexture)
  16260. */
  16261. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16262. if (compression === void 0) { compression = null; }
  16263. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16264. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16265. texture.baseWidth = width;
  16266. texture.baseHeight = height;
  16267. texture.baseDepth = depth;
  16268. texture.width = width;
  16269. texture.height = height;
  16270. texture.depth = depth;
  16271. texture.format = format;
  16272. texture.type = textureType;
  16273. texture.generateMipMaps = generateMipMaps;
  16274. texture.samplingMode = samplingMode;
  16275. texture.is3D = true;
  16276. if (!this._doNotHandleContextLost) {
  16277. texture._bufferView = data;
  16278. }
  16279. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16280. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16281. // Filters
  16282. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16283. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16284. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16285. if (generateMipMaps) {
  16286. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16287. }
  16288. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16289. this._internalTexturesCache.push(texture);
  16290. return texture;
  16291. };
  16292. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16293. var gl = this._gl;
  16294. if (!gl) {
  16295. return;
  16296. }
  16297. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16300. if (!noMipmap && !isCompressed) {
  16301. gl.generateMipmap(gl.TEXTURE_2D);
  16302. }
  16303. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16304. // this.resetTextureCache();
  16305. if (scene) {
  16306. scene._removePendingData(texture);
  16307. }
  16308. texture.onLoadedObservable.notifyObservers(texture);
  16309. texture.onLoadedObservable.clear();
  16310. };
  16311. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16312. var _this = this;
  16313. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16314. var maxTextureSize = this.getCaps().maxTextureSize;
  16315. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16316. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16317. var gl = this._gl;
  16318. if (!gl) {
  16319. return;
  16320. }
  16321. if (!texture._webGLTexture) {
  16322. // this.resetTextureCache();
  16323. if (scene) {
  16324. scene._removePendingData(texture);
  16325. }
  16326. return;
  16327. }
  16328. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16329. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16330. texture.baseWidth = width;
  16331. texture.baseHeight = height;
  16332. texture.width = potWidth;
  16333. texture.height = potHeight;
  16334. texture.isReady = true;
  16335. if (processFunction(potWidth, potHeight, function () {
  16336. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16337. })) {
  16338. // Returning as texture needs extra async steps
  16339. return;
  16340. }
  16341. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16342. };
  16343. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16344. // Create new RGBA data container.
  16345. var rgbaData;
  16346. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16347. rgbaData = new Float32Array(width * height * 4);
  16348. }
  16349. else {
  16350. rgbaData = new Uint32Array(width * height * 4);
  16351. }
  16352. // Convert each pixel.
  16353. for (var x = 0; x < width; x++) {
  16354. for (var y = 0; y < height; y++) {
  16355. var index = (y * width + x) * 3;
  16356. var newIndex = (y * width + x) * 4;
  16357. // Map Old Value to new value.
  16358. rgbaData[newIndex + 0] = rgbData[index + 0];
  16359. rgbaData[newIndex + 1] = rgbData[index + 1];
  16360. rgbaData[newIndex + 2] = rgbData[index + 2];
  16361. // Add fully opaque alpha channel.
  16362. rgbaData[newIndex + 3] = 1;
  16363. }
  16364. }
  16365. return rgbaData;
  16366. };
  16367. /** @hidden */
  16368. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16369. var gl = this._gl;
  16370. if (texture._framebuffer) {
  16371. gl.deleteFramebuffer(texture._framebuffer);
  16372. texture._framebuffer = null;
  16373. }
  16374. if (texture._depthStencilBuffer) {
  16375. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16376. texture._depthStencilBuffer = null;
  16377. }
  16378. if (texture._MSAAFramebuffer) {
  16379. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16380. texture._MSAAFramebuffer = null;
  16381. }
  16382. if (texture._MSAARenderBuffer) {
  16383. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16384. texture._MSAARenderBuffer = null;
  16385. }
  16386. };
  16387. /** @hidden */
  16388. Engine.prototype._releaseTexture = function (texture) {
  16389. var gl = this._gl;
  16390. this._releaseFramebufferObjects(texture);
  16391. gl.deleteTexture(texture._webGLTexture);
  16392. // Unbind channels
  16393. this.unbindAllTextures();
  16394. var index = this._internalTexturesCache.indexOf(texture);
  16395. if (index !== -1) {
  16396. this._internalTexturesCache.splice(index, 1);
  16397. }
  16398. // Integrated fixed lod samplers.
  16399. if (texture._lodTextureHigh) {
  16400. texture._lodTextureHigh.dispose();
  16401. }
  16402. if (texture._lodTextureMid) {
  16403. texture._lodTextureMid.dispose();
  16404. }
  16405. if (texture._lodTextureLow) {
  16406. texture._lodTextureLow.dispose();
  16407. }
  16408. // Set output texture of post process to null if the texture has been released/disposed
  16409. this.scenes.forEach(function (scene) {
  16410. scene.postProcesses.forEach(function (postProcess) {
  16411. if (postProcess._outputTexture == texture) {
  16412. postProcess._outputTexture = null;
  16413. }
  16414. });
  16415. scene.cameras.forEach(function (camera) {
  16416. camera._postProcesses.forEach(function (postProcess) {
  16417. if (postProcess) {
  16418. if (postProcess._outputTexture == texture) {
  16419. postProcess._outputTexture = null;
  16420. }
  16421. }
  16422. });
  16423. });
  16424. });
  16425. };
  16426. Engine.prototype.setProgram = function (program) {
  16427. if (this._currentProgram !== program) {
  16428. this._gl.useProgram(program);
  16429. this._currentProgram = program;
  16430. }
  16431. };
  16432. /**
  16433. * Binds an effect to the webGL context
  16434. * @param effect defines the effect to bind
  16435. */
  16436. Engine.prototype.bindSamplers = function (effect) {
  16437. this.setProgram(effect.getProgram());
  16438. var samplers = effect.getSamplers();
  16439. for (var index = 0; index < samplers.length; index++) {
  16440. var uniform = effect.getUniform(samplers[index]);
  16441. if (uniform) {
  16442. this._boundUniforms[index] = uniform;
  16443. }
  16444. }
  16445. this._currentEffect = null;
  16446. };
  16447. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16448. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16449. return;
  16450. }
  16451. // Remove
  16452. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16453. // Bind last to it
  16454. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16455. // Bind to dummy
  16456. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16457. };
  16458. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16459. if (!internalTexture) {
  16460. return -1;
  16461. }
  16462. internalTexture._initialSlot = channel;
  16463. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16464. if (channel !== internalTexture._designatedSlot) {
  16465. this._textureCollisions.addCount(1, false);
  16466. }
  16467. }
  16468. else {
  16469. if (channel !== internalTexture._designatedSlot) {
  16470. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16471. return internalTexture._designatedSlot;
  16472. }
  16473. else {
  16474. // No slot for this texture, let's pick a new one (if we find a free slot)
  16475. if (this._nextFreeTextureSlots.length) {
  16476. return this._nextFreeTextureSlots[0];
  16477. }
  16478. // We need to recycle the oldest bound texture, sorry.
  16479. this._textureCollisions.addCount(1, false);
  16480. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16481. }
  16482. }
  16483. }
  16484. return channel;
  16485. };
  16486. Engine.prototype._linkTrackers = function (previous, next) {
  16487. previous.next = next;
  16488. next.previous = previous;
  16489. };
  16490. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16491. var currentSlot = internalTexture._designatedSlot;
  16492. if (currentSlot === -1) {
  16493. return -1;
  16494. }
  16495. internalTexture._designatedSlot = -1;
  16496. if (this.disableTextureBindingOptimization) {
  16497. return -1;
  16498. }
  16499. // Remove from bound list
  16500. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16501. // Free the slot
  16502. this._boundTexturesCache[currentSlot] = null;
  16503. this._nextFreeTextureSlots.push(currentSlot);
  16504. return currentSlot;
  16505. };
  16506. Engine.prototype._activateCurrentTexture = function () {
  16507. if (this._currentTextureChannel !== this._activeChannel) {
  16508. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16509. this._currentTextureChannel = this._activeChannel;
  16510. }
  16511. };
  16512. /** @hidden */
  16513. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16514. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16515. if (force === void 0) { force = false; }
  16516. var wasPreviouslyBound = false;
  16517. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16518. this._activeChannel = texture._designatedSlot;
  16519. }
  16520. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16521. var isTextureForRendering = texture && texture._initialSlot > -1;
  16522. if (currentTextureBound !== texture || force) {
  16523. if (currentTextureBound) {
  16524. this._removeDesignatedSlot(currentTextureBound);
  16525. }
  16526. this._activateCurrentTexture();
  16527. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16528. this._boundTexturesCache[this._activeChannel] = texture;
  16529. if (texture) {
  16530. if (!this.disableTextureBindingOptimization) {
  16531. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16532. if (slotIndex > -1) {
  16533. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16534. }
  16535. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16536. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16537. }
  16538. texture._designatedSlot = this._activeChannel;
  16539. }
  16540. }
  16541. else if (forTextureDataUpdate) {
  16542. wasPreviouslyBound = true;
  16543. this._activateCurrentTexture();
  16544. }
  16545. if (isTextureForRendering && !forTextureDataUpdate) {
  16546. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16547. }
  16548. return wasPreviouslyBound;
  16549. };
  16550. /** @hidden */
  16551. Engine.prototype._bindTexture = function (channel, texture) {
  16552. if (channel < 0) {
  16553. return;
  16554. }
  16555. if (texture) {
  16556. channel = this._getCorrectTextureChannel(channel, texture);
  16557. }
  16558. this._activeChannel = channel;
  16559. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16560. };
  16561. /**
  16562. * Sets a texture to the webGL context from a postprocess
  16563. * @param channel defines the channel to use
  16564. * @param postProcess defines the source postprocess
  16565. */
  16566. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16567. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16568. };
  16569. /**
  16570. * Binds the output of the passed in post process to the texture channel specified
  16571. * @param channel The channel the texture should be bound to
  16572. * @param postProcess The post process which's output should be bound
  16573. */
  16574. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16575. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16576. };
  16577. /**
  16578. * Unbind all textures from the webGL context
  16579. */
  16580. Engine.prototype.unbindAllTextures = function () {
  16581. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16582. this._activeChannel = channel;
  16583. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16584. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16585. if (this.webGLVersion > 1) {
  16586. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16587. }
  16588. }
  16589. };
  16590. /**
  16591. * Sets a texture to the according uniform.
  16592. * @param channel The texture channel
  16593. * @param uniform The uniform to set
  16594. * @param texture The texture to apply
  16595. */
  16596. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16597. if (channel < 0) {
  16598. return;
  16599. }
  16600. if (uniform) {
  16601. this._boundUniforms[channel] = uniform;
  16602. }
  16603. this._setTexture(channel, texture);
  16604. };
  16605. /**
  16606. * Sets a depth stencil texture from a render target to the according uniform.
  16607. * @param channel The texture channel
  16608. * @param uniform The uniform to set
  16609. * @param texture The render target texture containing the depth stencil texture to apply
  16610. */
  16611. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16612. if (channel < 0) {
  16613. return;
  16614. }
  16615. if (uniform) {
  16616. this._boundUniforms[channel] = uniform;
  16617. }
  16618. if (!texture || !texture.depthStencilTexture) {
  16619. this._setTexture(channel, null);
  16620. }
  16621. else {
  16622. this._setTexture(channel, texture, false, true);
  16623. }
  16624. };
  16625. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16626. var uniform = this._boundUniforms[sourceSlot];
  16627. if (uniform._currentState === destination) {
  16628. return;
  16629. }
  16630. this._gl.uniform1i(uniform, destination);
  16631. uniform._currentState = destination;
  16632. };
  16633. Engine.prototype._getTextureWrapMode = function (mode) {
  16634. switch (mode) {
  16635. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16636. return this._gl.REPEAT;
  16637. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16638. return this._gl.CLAMP_TO_EDGE;
  16639. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16640. return this._gl.MIRRORED_REPEAT;
  16641. }
  16642. return this._gl.REPEAT;
  16643. };
  16644. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16645. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16646. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16647. // Not ready?
  16648. if (!texture) {
  16649. if (this._boundTexturesCache[channel] != null) {
  16650. this._activeChannel = channel;
  16651. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16652. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16653. if (this.webGLVersion > 1) {
  16654. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16655. }
  16656. }
  16657. return false;
  16658. }
  16659. // Video
  16660. if (texture.video) {
  16661. this._activeChannel = channel;
  16662. texture.update();
  16663. }
  16664. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16665. texture.delayLoad();
  16666. return false;
  16667. }
  16668. var internalTexture;
  16669. if (depthStencilTexture) {
  16670. internalTexture = texture.depthStencilTexture;
  16671. }
  16672. else if (texture.isReady()) {
  16673. internalTexture = texture.getInternalTexture();
  16674. }
  16675. else if (texture.isCube) {
  16676. internalTexture = this.emptyCubeTexture;
  16677. }
  16678. else if (texture.is3D) {
  16679. internalTexture = this.emptyTexture3D;
  16680. }
  16681. else {
  16682. internalTexture = this.emptyTexture;
  16683. }
  16684. if (!isPartOfTextureArray) {
  16685. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16686. }
  16687. var needToBind = true;
  16688. if (this._boundTexturesCache[channel] === internalTexture) {
  16689. this._moveBoundTextureOnTop(internalTexture);
  16690. if (!isPartOfTextureArray) {
  16691. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16692. }
  16693. needToBind = false;
  16694. }
  16695. this._activeChannel = channel;
  16696. if (internalTexture && internalTexture.is3D) {
  16697. if (needToBind) {
  16698. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16699. }
  16700. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16701. internalTexture._cachedWrapU = texture.wrapU;
  16702. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16703. }
  16704. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16705. internalTexture._cachedWrapV = texture.wrapV;
  16706. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16707. }
  16708. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16709. internalTexture._cachedWrapR = texture.wrapR;
  16710. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16711. }
  16712. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16713. }
  16714. else if (internalTexture && internalTexture.isCube) {
  16715. if (needToBind) {
  16716. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16717. }
  16718. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16719. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16720. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16721. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16722. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16723. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16724. }
  16725. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16726. }
  16727. else {
  16728. if (needToBind) {
  16729. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16730. }
  16731. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16732. internalTexture._cachedWrapU = texture.wrapU;
  16733. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16734. }
  16735. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16736. internalTexture._cachedWrapV = texture.wrapV;
  16737. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16738. }
  16739. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16740. }
  16741. return true;
  16742. };
  16743. /**
  16744. * Sets an array of texture to the webGL context
  16745. * @param channel defines the channel where the texture array must be set
  16746. * @param uniform defines the associated uniform location
  16747. * @param textures defines the array of textures to bind
  16748. */
  16749. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16750. if (channel < 0 || !uniform) {
  16751. return;
  16752. }
  16753. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16754. this._textureUnits = new Int32Array(textures.length);
  16755. }
  16756. for (var i = 0; i < textures.length; i++) {
  16757. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16758. }
  16759. this._gl.uniform1iv(uniform, this._textureUnits);
  16760. for (var index = 0; index < textures.length; index++) {
  16761. this._setTexture(this._textureUnits[index], textures[index], true);
  16762. }
  16763. };
  16764. /** @hidden */
  16765. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16766. var internalTexture = texture.getInternalTexture();
  16767. if (!internalTexture) {
  16768. return;
  16769. }
  16770. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16771. var value = texture.anisotropicFilteringLevel;
  16772. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16773. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16774. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16775. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16776. }
  16777. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16778. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16779. internalTexture._cachedAnisotropicFilteringLevel = value;
  16780. }
  16781. };
  16782. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16783. this._bindTextureDirectly(target, texture, true, true);
  16784. this._gl.texParameterf(target, parameter, value);
  16785. };
  16786. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16787. if (texture) {
  16788. this._bindTextureDirectly(target, texture, true, true);
  16789. }
  16790. this._gl.texParameteri(target, parameter, value);
  16791. };
  16792. /**
  16793. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16794. * @param x defines the x coordinate of the rectangle where pixels must be read
  16795. * @param y defines the y coordinate of the rectangle where pixels must be read
  16796. * @param width defines the width of the rectangle where pixels must be read
  16797. * @param height defines the height of the rectangle where pixels must be read
  16798. * @returns a Uint8Array containing RGBA colors
  16799. */
  16800. Engine.prototype.readPixels = function (x, y, width, height) {
  16801. var data = new Uint8Array(height * width * 4);
  16802. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16803. return data;
  16804. };
  16805. /**
  16806. * Add an externaly attached data from its key.
  16807. * This method call will fail and return false, if such key already exists.
  16808. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16809. * @param key the unique key that identifies the data
  16810. * @param data the data object to associate to the key for this Engine instance
  16811. * @return true if no such key were already present and the data was added successfully, false otherwise
  16812. */
  16813. Engine.prototype.addExternalData = function (key, data) {
  16814. if (!this._externalData) {
  16815. this._externalData = new BABYLON.StringDictionary();
  16816. }
  16817. return this._externalData.add(key, data);
  16818. };
  16819. /**
  16820. * Get an externaly attached data from its key
  16821. * @param key the unique key that identifies the data
  16822. * @return the associated data, if present (can be null), or undefined if not present
  16823. */
  16824. Engine.prototype.getExternalData = function (key) {
  16825. if (!this._externalData) {
  16826. this._externalData = new BABYLON.StringDictionary();
  16827. }
  16828. return this._externalData.get(key);
  16829. };
  16830. /**
  16831. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16832. * @param key the unique key that identifies the data
  16833. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16834. * @return the associated data, can be null if the factory returned null.
  16835. */
  16836. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16837. if (!this._externalData) {
  16838. this._externalData = new BABYLON.StringDictionary();
  16839. }
  16840. return this._externalData.getOrAddWithFactory(key, factory);
  16841. };
  16842. /**
  16843. * Remove an externaly attached data from the Engine instance
  16844. * @param key the unique key that identifies the data
  16845. * @return true if the data was successfully removed, false if it doesn't exist
  16846. */
  16847. Engine.prototype.removeExternalData = function (key) {
  16848. if (!this._externalData) {
  16849. this._externalData = new BABYLON.StringDictionary();
  16850. }
  16851. return this._externalData.remove(key);
  16852. };
  16853. /**
  16854. * Unbind all vertex attributes from the webGL context
  16855. */
  16856. Engine.prototype.unbindAllAttributes = function () {
  16857. if (this._mustWipeVertexAttributes) {
  16858. this._mustWipeVertexAttributes = false;
  16859. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16860. this._gl.disableVertexAttribArray(i);
  16861. this._vertexAttribArraysEnabled[i] = false;
  16862. this._currentBufferPointers[i].active = false;
  16863. }
  16864. return;
  16865. }
  16866. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16867. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16868. continue;
  16869. }
  16870. this._gl.disableVertexAttribArray(i);
  16871. this._vertexAttribArraysEnabled[i] = false;
  16872. this._currentBufferPointers[i].active = false;
  16873. }
  16874. };
  16875. /**
  16876. * 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
  16877. */
  16878. Engine.prototype.releaseEffects = function () {
  16879. for (var name in this._compiledEffects) {
  16880. this._deleteProgram(this._compiledEffects[name]._program);
  16881. }
  16882. this._compiledEffects = {};
  16883. };
  16884. /**
  16885. * Dispose and release all associated resources
  16886. */
  16887. Engine.prototype.dispose = function () {
  16888. this.hideLoadingUI();
  16889. this.stopRenderLoop();
  16890. // Release postProcesses
  16891. while (this.postProcesses.length) {
  16892. this.postProcesses[0].dispose();
  16893. }
  16894. // Empty texture
  16895. if (this._emptyTexture) {
  16896. this._releaseTexture(this._emptyTexture);
  16897. this._emptyTexture = null;
  16898. }
  16899. if (this._emptyCubeTexture) {
  16900. this._releaseTexture(this._emptyCubeTexture);
  16901. this._emptyCubeTexture = null;
  16902. }
  16903. // Rescale PP
  16904. if (this._rescalePostProcess) {
  16905. this._rescalePostProcess.dispose();
  16906. }
  16907. // Release scenes
  16908. while (this.scenes.length) {
  16909. this.scenes[0].dispose();
  16910. }
  16911. // Release audio engine
  16912. if (Engine.audioEngine) {
  16913. Engine.audioEngine.dispose();
  16914. }
  16915. // Release effects
  16916. this.releaseEffects();
  16917. // Unbind
  16918. this.unbindAllAttributes();
  16919. this._boundUniforms = [];
  16920. if (this._dummyFramebuffer) {
  16921. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16922. }
  16923. //WebVR
  16924. this.disableVR();
  16925. // Events
  16926. if (BABYLON.Tools.IsWindowObjectExist()) {
  16927. window.removeEventListener("blur", this._onBlur);
  16928. window.removeEventListener("focus", this._onFocus);
  16929. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16930. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16931. if (this._renderingCanvas) {
  16932. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16933. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16934. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16935. if (!this._doNotHandleContextLost) {
  16936. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16937. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16938. }
  16939. }
  16940. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16941. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16942. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16943. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16944. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16945. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16946. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16947. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16948. if (this._onVrDisplayConnect) {
  16949. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16950. if (this._onVrDisplayDisconnect) {
  16951. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16952. }
  16953. if (this._onVrDisplayPresentChange) {
  16954. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16955. }
  16956. this._onVrDisplayConnect = null;
  16957. this._onVrDisplayDisconnect = null;
  16958. }
  16959. }
  16960. // Remove from Instances
  16961. var index = Engine.Instances.indexOf(this);
  16962. if (index >= 0) {
  16963. Engine.Instances.splice(index, 1);
  16964. }
  16965. this._workingCanvas = null;
  16966. this._workingContext = null;
  16967. this._currentBufferPointers = [];
  16968. this._renderingCanvas = null;
  16969. this._currentProgram = null;
  16970. this._bindedRenderFunction = null;
  16971. this.onResizeObservable.clear();
  16972. this.onCanvasBlurObservable.clear();
  16973. this.onCanvasFocusObservable.clear();
  16974. this.onCanvasPointerOutObservable.clear();
  16975. this.onBeginFrameObservable.clear();
  16976. this.onEndFrameObservable.clear();
  16977. BABYLON.Effect.ResetCache();
  16978. // Abort active requests
  16979. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16980. var request = _a[_i];
  16981. request.abort();
  16982. }
  16983. };
  16984. // Loading screen
  16985. /**
  16986. * Display the loading screen
  16987. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16988. */
  16989. Engine.prototype.displayLoadingUI = function () {
  16990. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16991. return;
  16992. }
  16993. var loadingScreen = this.loadingScreen;
  16994. if (loadingScreen) {
  16995. loadingScreen.displayLoadingUI();
  16996. }
  16997. };
  16998. /**
  16999. * Hide the loading screen
  17000. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17001. */
  17002. Engine.prototype.hideLoadingUI = function () {
  17003. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17004. return;
  17005. }
  17006. var loadingScreen = this.loadingScreen;
  17007. if (loadingScreen) {
  17008. loadingScreen.hideLoadingUI();
  17009. }
  17010. };
  17011. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17012. /**
  17013. * Gets the current loading screen object
  17014. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17015. */
  17016. get: function () {
  17017. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17018. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17019. return this._loadingScreen;
  17020. },
  17021. /**
  17022. * Sets the current loading screen object
  17023. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17024. */
  17025. set: function (loadingScreen) {
  17026. this._loadingScreen = loadingScreen;
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17032. /**
  17033. * Sets the current loading screen text
  17034. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17035. */
  17036. set: function (text) {
  17037. this.loadingScreen.loadingUIText = text;
  17038. },
  17039. enumerable: true,
  17040. configurable: true
  17041. });
  17042. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17043. /**
  17044. * Sets the current loading screen background color
  17045. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17046. */
  17047. set: function (color) {
  17048. this.loadingScreen.loadingUIBackgroundColor = color;
  17049. },
  17050. enumerable: true,
  17051. configurable: true
  17052. });
  17053. /**
  17054. * Attach a new callback raised when context lost event is fired
  17055. * @param callback defines the callback to call
  17056. */
  17057. Engine.prototype.attachContextLostEvent = function (callback) {
  17058. if (this._renderingCanvas) {
  17059. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17060. }
  17061. };
  17062. /**
  17063. * Attach a new callback raised when context restored event is fired
  17064. * @param callback defines the callback to call
  17065. */
  17066. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17067. if (this._renderingCanvas) {
  17068. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17069. }
  17070. };
  17071. /**
  17072. * Gets the source code of the vertex shader associated with a specific webGL program
  17073. * @param program defines the program to use
  17074. * @returns a string containing the source code of the vertex shader associated with the program
  17075. */
  17076. Engine.prototype.getVertexShaderSource = function (program) {
  17077. var shaders = this._gl.getAttachedShaders(program);
  17078. if (!shaders) {
  17079. return null;
  17080. }
  17081. return this._gl.getShaderSource(shaders[0]);
  17082. };
  17083. /**
  17084. * Gets the source code of the fragment shader associated with a specific webGL program
  17085. * @param program defines the program to use
  17086. * @returns a string containing the source code of the fragment shader associated with the program
  17087. */
  17088. Engine.prototype.getFragmentShaderSource = function (program) {
  17089. var shaders = this._gl.getAttachedShaders(program);
  17090. if (!shaders) {
  17091. return null;
  17092. }
  17093. return this._gl.getShaderSource(shaders[1]);
  17094. };
  17095. /**
  17096. * Get the current error code of the webGL context
  17097. * @returns the error code
  17098. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17099. */
  17100. Engine.prototype.getError = function () {
  17101. return this._gl.getError();
  17102. };
  17103. // FPS
  17104. /**
  17105. * Gets the current framerate
  17106. * @returns a number representing the framerate
  17107. */
  17108. Engine.prototype.getFps = function () {
  17109. return this._fps;
  17110. };
  17111. /**
  17112. * Gets the time spent between current and previous frame
  17113. * @returns a number representing the delta time in ms
  17114. */
  17115. Engine.prototype.getDeltaTime = function () {
  17116. return this._deltaTime;
  17117. };
  17118. Engine.prototype._measureFps = function () {
  17119. this._performanceMonitor.sampleFrame();
  17120. this._fps = this._performanceMonitor.averageFPS;
  17121. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17122. };
  17123. /** @hidden */
  17124. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17125. if (faceIndex === void 0) { faceIndex = -1; }
  17126. if (level === void 0) { level = 0; }
  17127. var gl = this._gl;
  17128. if (!this._dummyFramebuffer) {
  17129. var dummy = gl.createFramebuffer();
  17130. if (!dummy) {
  17131. throw new Error("Unable to create dummy framebuffer");
  17132. }
  17133. this._dummyFramebuffer = dummy;
  17134. }
  17135. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17136. if (faceIndex > -1) {
  17137. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17138. }
  17139. else {
  17140. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17141. }
  17142. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17143. var buffer;
  17144. switch (readType) {
  17145. case gl.UNSIGNED_BYTE:
  17146. buffer = new Uint8Array(4 * width * height);
  17147. readType = gl.UNSIGNED_BYTE;
  17148. break;
  17149. default:
  17150. buffer = new Float32Array(4 * width * height);
  17151. readType = gl.FLOAT;
  17152. break;
  17153. }
  17154. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17155. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17156. return buffer;
  17157. };
  17158. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17159. if (this._webGLVersion > 1) {
  17160. return this._caps.colorBufferFloat;
  17161. }
  17162. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17163. };
  17164. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17165. if (this._webGLVersion > 1) {
  17166. return this._caps.colorBufferFloat;
  17167. }
  17168. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17169. };
  17170. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17171. Engine.prototype._canRenderToFramebuffer = function (type) {
  17172. var gl = this._gl;
  17173. //clear existing errors
  17174. while (gl.getError() !== gl.NO_ERROR) { }
  17175. var successful = true;
  17176. var texture = gl.createTexture();
  17177. gl.bindTexture(gl.TEXTURE_2D, texture);
  17178. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17181. var fb = gl.createFramebuffer();
  17182. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17183. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17184. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17185. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17186. successful = successful && (gl.getError() === gl.NO_ERROR);
  17187. //try render by clearing frame buffer's color buffer
  17188. if (successful) {
  17189. gl.clear(gl.COLOR_BUFFER_BIT);
  17190. successful = successful && (gl.getError() === gl.NO_ERROR);
  17191. }
  17192. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17193. if (successful) {
  17194. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17195. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17196. var readFormat = gl.RGBA;
  17197. var readType = gl.UNSIGNED_BYTE;
  17198. var buffer = new Uint8Array(4);
  17199. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17200. successful = successful && (gl.getError() === gl.NO_ERROR);
  17201. }
  17202. //clean up
  17203. gl.deleteTexture(texture);
  17204. gl.deleteFramebuffer(fb);
  17205. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17206. //clear accumulated errors
  17207. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17208. return successful;
  17209. };
  17210. /** @hidden */
  17211. Engine.prototype._getWebGLTextureType = function (type) {
  17212. if (type === Engine.TEXTURETYPE_FLOAT) {
  17213. return this._gl.FLOAT;
  17214. }
  17215. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17216. // Add Half Float Constant.
  17217. return this._gl.HALF_FLOAT_OES;
  17218. }
  17219. return this._gl.UNSIGNED_BYTE;
  17220. };
  17221. ;
  17222. Engine.prototype._getInternalFormat = function (format) {
  17223. var internalFormat = this._gl.RGBA;
  17224. switch (format) {
  17225. case Engine.TEXTUREFORMAT_ALPHA:
  17226. internalFormat = this._gl.ALPHA;
  17227. break;
  17228. case Engine.TEXTUREFORMAT_LUMINANCE:
  17229. internalFormat = this._gl.LUMINANCE;
  17230. break;
  17231. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17232. internalFormat = this._gl.LUMINANCE_ALPHA;
  17233. break;
  17234. case Engine.TEXTUREFORMAT_RGB:
  17235. internalFormat = this._gl.RGB;
  17236. break;
  17237. case Engine.TEXTUREFORMAT_RGBA:
  17238. internalFormat = this._gl.RGBA;
  17239. break;
  17240. case Engine.TEXTUREFORMAT_R:
  17241. internalFormat = this._gl.RED;
  17242. break;
  17243. case Engine.TEXTUREFORMAT_RG:
  17244. internalFormat = this._gl.RG;
  17245. break;
  17246. }
  17247. return internalFormat;
  17248. };
  17249. /** @hidden */
  17250. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17251. if (this._webGLVersion === 1) {
  17252. if (format !== undefined) {
  17253. switch (format) {
  17254. case Engine.TEXTUREFORMAT_LUMINANCE:
  17255. return this._gl.LUMINANCE;
  17256. case Engine.TEXTUREFORMAT_ALPHA:
  17257. return this._gl.ALPHA;
  17258. }
  17259. }
  17260. return this._gl.RGBA;
  17261. }
  17262. if (type === Engine.TEXTURETYPE_FLOAT) {
  17263. if (format !== undefined) {
  17264. switch (format) {
  17265. case Engine.TEXTUREFORMAT_R:
  17266. return this._gl.R32F;
  17267. case Engine.TEXTUREFORMAT_RG:
  17268. return this._gl.RG32F;
  17269. case Engine.TEXTUREFORMAT_RGB:
  17270. return this._gl.RGB32F;
  17271. }
  17272. }
  17273. return this._gl.RGBA32F;
  17274. }
  17275. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17276. if (format) {
  17277. switch (format) {
  17278. case Engine.TEXTUREFORMAT_R:
  17279. return this._gl.R16F;
  17280. case Engine.TEXTUREFORMAT_RG:
  17281. return this._gl.RG16F;
  17282. case Engine.TEXTUREFORMAT_RGB:
  17283. return this._gl.RGB16F;
  17284. }
  17285. }
  17286. return this._gl.RGBA16F;
  17287. }
  17288. if (format !== undefined) {
  17289. switch (format) {
  17290. case Engine.TEXTUREFORMAT_LUMINANCE:
  17291. return this._gl.LUMINANCE;
  17292. case Engine.TEXTUREFORMAT_RGB:
  17293. return this._gl.RGB;
  17294. case Engine.TEXTUREFORMAT_R:
  17295. return this._gl.R8;
  17296. case Engine.TEXTUREFORMAT_RG:
  17297. return this._gl.RG8;
  17298. case Engine.TEXTUREFORMAT_ALPHA:
  17299. return this._gl.ALPHA;
  17300. }
  17301. }
  17302. return this._gl.RGBA;
  17303. };
  17304. ;
  17305. /** @hidden */
  17306. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17307. if (type === Engine.TEXTURETYPE_FLOAT) {
  17308. return this._gl.RGBA32F;
  17309. }
  17310. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17311. return this._gl.RGBA16F;
  17312. }
  17313. return this._gl.RGBA8;
  17314. };
  17315. ;
  17316. /**
  17317. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17318. * @return the new query
  17319. */
  17320. Engine.prototype.createQuery = function () {
  17321. return this._gl.createQuery();
  17322. };
  17323. /**
  17324. * Delete and release a webGL query
  17325. * @param query defines the query to delete
  17326. * @return the current engine
  17327. */
  17328. Engine.prototype.deleteQuery = function (query) {
  17329. this._gl.deleteQuery(query);
  17330. return this;
  17331. };
  17332. /**
  17333. * Check if a given query has resolved and got its value
  17334. * @param query defines the query to check
  17335. * @returns true if the query got its value
  17336. */
  17337. Engine.prototype.isQueryResultAvailable = function (query) {
  17338. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17339. };
  17340. /**
  17341. * Gets the value of a given query
  17342. * @param query defines the query to check
  17343. * @returns the value of the query
  17344. */
  17345. Engine.prototype.getQueryResult = function (query) {
  17346. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17347. };
  17348. /**
  17349. * Initiates an occlusion query
  17350. * @param algorithmType defines the algorithm to use
  17351. * @param query defines the query to use
  17352. * @returns the current engine
  17353. * @see http://doc.babylonjs.com/features/occlusionquery
  17354. */
  17355. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17356. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17357. this._gl.beginQuery(glAlgorithm, query);
  17358. return this;
  17359. };
  17360. /**
  17361. * Ends an occlusion query
  17362. * @see http://doc.babylonjs.com/features/occlusionquery
  17363. * @param algorithmType defines the algorithm to use
  17364. * @returns the current engine
  17365. */
  17366. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17367. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17368. this._gl.endQuery(glAlgorithm);
  17369. return this;
  17370. };
  17371. /* Time queries */
  17372. Engine.prototype._createTimeQuery = function () {
  17373. var timerQuery = this._caps.timerQuery;
  17374. if (timerQuery.createQueryEXT) {
  17375. return timerQuery.createQueryEXT();
  17376. }
  17377. return this.createQuery();
  17378. };
  17379. Engine.prototype._deleteTimeQuery = function (query) {
  17380. var timerQuery = this._caps.timerQuery;
  17381. if (timerQuery.deleteQueryEXT) {
  17382. timerQuery.deleteQueryEXT(query);
  17383. return;
  17384. }
  17385. this.deleteQuery(query);
  17386. };
  17387. Engine.prototype._getTimeQueryResult = function (query) {
  17388. var timerQuery = this._caps.timerQuery;
  17389. if (timerQuery.getQueryObjectEXT) {
  17390. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17391. }
  17392. return this.getQueryResult(query);
  17393. };
  17394. Engine.prototype._getTimeQueryAvailability = function (query) {
  17395. var timerQuery = this._caps.timerQuery;
  17396. if (timerQuery.getQueryObjectEXT) {
  17397. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17398. }
  17399. return this.isQueryResultAvailable(query);
  17400. };
  17401. /**
  17402. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17403. * Please note that only one query can be issued at a time
  17404. * @returns a time token used to track the time span
  17405. */
  17406. Engine.prototype.startTimeQuery = function () {
  17407. var timerQuery = this._caps.timerQuery;
  17408. if (!timerQuery) {
  17409. return null;
  17410. }
  17411. var token = new BABYLON._TimeToken();
  17412. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17413. if (this._caps.canUseTimestampForTimerQuery) {
  17414. token._startTimeQuery = this._createTimeQuery();
  17415. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17416. }
  17417. else {
  17418. if (this._currentNonTimestampToken) {
  17419. return this._currentNonTimestampToken;
  17420. }
  17421. token._timeElapsedQuery = this._createTimeQuery();
  17422. if (timerQuery.beginQueryEXT) {
  17423. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17424. }
  17425. else {
  17426. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17427. }
  17428. this._currentNonTimestampToken = token;
  17429. }
  17430. return token;
  17431. };
  17432. /**
  17433. * Ends a time query
  17434. * @param token defines the token used to measure the time span
  17435. * @returns the time spent (in ns)
  17436. */
  17437. Engine.prototype.endTimeQuery = function (token) {
  17438. var timerQuery = this._caps.timerQuery;
  17439. if (!timerQuery || !token) {
  17440. return -1;
  17441. }
  17442. if (this._caps.canUseTimestampForTimerQuery) {
  17443. if (!token._startTimeQuery) {
  17444. return -1;
  17445. }
  17446. if (!token._endTimeQuery) {
  17447. token._endTimeQuery = this._createTimeQuery();
  17448. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17449. }
  17450. }
  17451. else if (!token._timeElapsedQueryEnded) {
  17452. if (!token._timeElapsedQuery) {
  17453. return -1;
  17454. }
  17455. if (timerQuery.endQueryEXT) {
  17456. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17457. }
  17458. else {
  17459. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17460. }
  17461. token._timeElapsedQueryEnded = true;
  17462. }
  17463. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17464. var available = false;
  17465. if (token._endTimeQuery) {
  17466. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17467. }
  17468. else if (token._timeElapsedQuery) {
  17469. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17470. }
  17471. if (available && !disjoint) {
  17472. var result = 0;
  17473. if (this._caps.canUseTimestampForTimerQuery) {
  17474. if (!token._startTimeQuery || !token._endTimeQuery) {
  17475. return -1;
  17476. }
  17477. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17478. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17479. result = timeEnd - timeStart;
  17480. this._deleteTimeQuery(token._startTimeQuery);
  17481. this._deleteTimeQuery(token._endTimeQuery);
  17482. token._startTimeQuery = null;
  17483. token._endTimeQuery = null;
  17484. }
  17485. else {
  17486. if (!token._timeElapsedQuery) {
  17487. return -1;
  17488. }
  17489. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17490. this._deleteTimeQuery(token._timeElapsedQuery);
  17491. token._timeElapsedQuery = null;
  17492. token._timeElapsedQueryEnded = false;
  17493. this._currentNonTimestampToken = null;
  17494. }
  17495. return result;
  17496. }
  17497. return -1;
  17498. };
  17499. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17500. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17501. };
  17502. // Transform feedback
  17503. /**
  17504. * Creates a webGL transform feedback object
  17505. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17506. * @returns the webGL transform feedback object
  17507. */
  17508. Engine.prototype.createTransformFeedback = function () {
  17509. return this._gl.createTransformFeedback();
  17510. };
  17511. /**
  17512. * Delete a webGL transform feedback object
  17513. * @param value defines the webGL transform feedback object to delete
  17514. */
  17515. Engine.prototype.deleteTransformFeedback = function (value) {
  17516. this._gl.deleteTransformFeedback(value);
  17517. };
  17518. /**
  17519. * Bind a webGL transform feedback object to the webgl context
  17520. * @param value defines the webGL transform feedback object to bind
  17521. */
  17522. Engine.prototype.bindTransformFeedback = function (value) {
  17523. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17524. };
  17525. /**
  17526. * Begins a transform feedback operation
  17527. * @param usePoints defines if points or triangles must be used
  17528. */
  17529. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17530. if (usePoints === void 0) { usePoints = true; }
  17531. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17532. };
  17533. /**
  17534. * Ends a transform feedback operation
  17535. */
  17536. Engine.prototype.endTransformFeedback = function () {
  17537. this._gl.endTransformFeedback();
  17538. };
  17539. /**
  17540. * Specify the varyings to use with transform feedback
  17541. * @param program defines the associated webGL program
  17542. * @param value defines the list of strings representing the varying names
  17543. */
  17544. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17545. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17546. };
  17547. /**
  17548. * Bind a webGL buffer for a transform feedback operation
  17549. * @param value defines the webGL buffer to bind
  17550. */
  17551. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17552. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17553. };
  17554. /** @hidden */
  17555. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17556. var _this = this;
  17557. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17558. this._activeRequests.push(request);
  17559. request.onCompleteObservable.add(function (request) {
  17560. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17561. });
  17562. return request;
  17563. };
  17564. /** @hidden */
  17565. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17566. var _this = this;
  17567. return new Promise(function (resolve, reject) {
  17568. _this._loadFile(url, function (data) {
  17569. resolve(data);
  17570. }, undefined, database, useArrayBuffer, function (request, exception) {
  17571. reject(exception);
  17572. });
  17573. });
  17574. };
  17575. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17576. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17577. var onload = function (data) {
  17578. loadedFiles[index] = data;
  17579. loadedFiles._internalCount++;
  17580. if (loadedFiles._internalCount === 6) {
  17581. onfinish(loadedFiles);
  17582. }
  17583. };
  17584. var onerror = function (request, exception) {
  17585. if (onErrorCallBack && request) {
  17586. onErrorCallBack(request.status + " " + request.statusText, exception);
  17587. }
  17588. };
  17589. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17590. };
  17591. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17592. if (onError === void 0) { onError = null; }
  17593. var loadedFiles = [];
  17594. loadedFiles._internalCount = 0;
  17595. for (var index = 0; index < 6; index++) {
  17596. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17597. }
  17598. };
  17599. // Statics
  17600. /**
  17601. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17602. * @returns true if the engine can be created
  17603. * @ignorenaming
  17604. */
  17605. Engine.isSupported = function () {
  17606. try {
  17607. var tempcanvas = document.createElement("canvas");
  17608. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17609. return gl != null && !!window.WebGLRenderingContext;
  17610. }
  17611. catch (e) {
  17612. return false;
  17613. }
  17614. };
  17615. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17616. Engine.ExceptionList = [
  17617. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17618. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17619. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17620. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17621. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17622. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17623. ];
  17624. /** Gets the list of created engines */
  17625. Engine.Instances = new Array();
  17626. // Const statics
  17627. Engine._ALPHA_DISABLE = 0;
  17628. Engine._ALPHA_ADD = 1;
  17629. Engine._ALPHA_COMBINE = 2;
  17630. Engine._ALPHA_SUBTRACT = 3;
  17631. Engine._ALPHA_MULTIPLY = 4;
  17632. Engine._ALPHA_MAXIMIZED = 5;
  17633. Engine._ALPHA_ONEONE = 6;
  17634. Engine._ALPHA_PREMULTIPLIED = 7;
  17635. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17636. Engine._ALPHA_INTERPOLATE = 9;
  17637. Engine._ALPHA_SCREENMODE = 10;
  17638. Engine._DELAYLOADSTATE_NONE = 0;
  17639. Engine._DELAYLOADSTATE_LOADED = 1;
  17640. Engine._DELAYLOADSTATE_LOADING = 2;
  17641. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17642. Engine._TEXTUREFORMAT_ALPHA = 0;
  17643. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17644. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17645. Engine._TEXTUREFORMAT_RGB = 4;
  17646. Engine._TEXTUREFORMAT_RGBA = 5;
  17647. Engine._TEXTUREFORMAT_R = 6;
  17648. Engine._TEXTUREFORMAT_RG = 7;
  17649. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17650. Engine._TEXTURETYPE_FLOAT = 1;
  17651. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17652. // Depht or Stencil test Constants.
  17653. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17654. 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.
  17655. 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.
  17656. 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.
  17657. 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.
  17658. 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.
  17659. 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.
  17660. 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.
  17661. // Stencil Actions Constants.
  17662. Engine._KEEP = 0x1E00;
  17663. Engine._REPLACE = 0x1E01;
  17664. Engine._INCR = 0x1E02;
  17665. Engine._DECR = 0x1E03;
  17666. Engine._INVERT = 0x150A;
  17667. Engine._INCR_WRAP = 0x8507;
  17668. Engine._DECR_WRAP = 0x8508;
  17669. // Texture rescaling mode
  17670. Engine._SCALEMODE_FLOOR = 1;
  17671. Engine._SCALEMODE_NEAREST = 2;
  17672. Engine._SCALEMODE_CEILING = 3;
  17673. // Updatable statics so stick with vars here
  17674. /**
  17675. * Gets or sets the epsilon value used by collision engine
  17676. */
  17677. Engine.CollisionsEpsilon = 0.001;
  17678. /**
  17679. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17680. */
  17681. Engine.CodeRepository = "src/";
  17682. /**
  17683. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17684. */
  17685. Engine.ShadersRepository = "src/Shaders/";
  17686. return Engine;
  17687. }());
  17688. BABYLON.Engine = Engine;
  17689. })(BABYLON || (BABYLON = {}));
  17690. //# sourceMappingURL=babylon.engine.js.map
  17691. var BABYLON;
  17692. (function (BABYLON) {
  17693. /**
  17694. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17695. */
  17696. var Node = /** @class */ (function () {
  17697. /**
  17698. * Creates a new Node
  17699. * @param {string} name - the name and id to be given to this node
  17700. * @param {BABYLON.Scene} the scene this node will be added to
  17701. */
  17702. function Node(name, scene) {
  17703. if (scene === void 0) { scene = null; }
  17704. /**
  17705. * Gets or sets a string used to store user defined state for the node
  17706. */
  17707. this.state = "";
  17708. /**
  17709. * Gets or sets an object used to store user defined information for the node
  17710. */
  17711. this.metadata = null;
  17712. /**
  17713. * Gets or sets a boolean used to define if the node must be serialized
  17714. */
  17715. this.doNotSerialize = false;
  17716. /** @hidden */
  17717. this._isDisposed = false;
  17718. /**
  17719. * Gets a list of Animations associated with the node
  17720. */
  17721. this.animations = new Array();
  17722. this._ranges = {};
  17723. this._isEnabled = true;
  17724. this._isReady = true;
  17725. /** @hidden */
  17726. this._currentRenderId = -1;
  17727. this._parentRenderId = -1;
  17728. this._childRenderId = -1;
  17729. this._animationPropertiesOverride = null;
  17730. /**
  17731. * An event triggered when the mesh is disposed
  17732. */
  17733. this.onDisposeObservable = new BABYLON.Observable();
  17734. // Behaviors
  17735. this._behaviors = new Array();
  17736. this.name = name;
  17737. this.id = name;
  17738. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17739. this.uniqueId = this._scene.getUniqueId();
  17740. this._initCache();
  17741. }
  17742. /**
  17743. * Gets a boolean indicating if the node has been disposed
  17744. * @returns true if the node was disposed
  17745. */
  17746. Node.prototype.isDisposed = function () {
  17747. return this._isDisposed;
  17748. };
  17749. Object.defineProperty(Node.prototype, "parent", {
  17750. get: function () {
  17751. return this._parentNode;
  17752. },
  17753. /**
  17754. * Gets or sets the parent of the node
  17755. */
  17756. set: function (parent) {
  17757. if (this._parentNode === parent) {
  17758. return;
  17759. }
  17760. // Remove self from list of children of parent
  17761. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17762. var index = this._parentNode._children.indexOf(this);
  17763. if (index !== -1) {
  17764. this._parentNode._children.splice(index, 1);
  17765. }
  17766. }
  17767. // Store new parent
  17768. this._parentNode = parent;
  17769. // Add as child to new parent
  17770. if (this._parentNode) {
  17771. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17772. this._parentNode._children = new Array();
  17773. }
  17774. this._parentNode._children.push(this);
  17775. }
  17776. },
  17777. enumerable: true,
  17778. configurable: true
  17779. });
  17780. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17781. /**
  17782. * Gets or sets the animation properties override
  17783. */
  17784. get: function () {
  17785. if (!this._animationPropertiesOverride) {
  17786. return this._scene.animationPropertiesOverride;
  17787. }
  17788. return this._animationPropertiesOverride;
  17789. },
  17790. set: function (value) {
  17791. this._animationPropertiesOverride = value;
  17792. },
  17793. enumerable: true,
  17794. configurable: true
  17795. });
  17796. /**
  17797. * Gets a string idenfifying the name of the class
  17798. * @returns "Node" string
  17799. */
  17800. Node.prototype.getClassName = function () {
  17801. return "Node";
  17802. };
  17803. Object.defineProperty(Node.prototype, "onDispose", {
  17804. /**
  17805. * Sets a callback that will be raised when the node will be disposed
  17806. */
  17807. set: function (callback) {
  17808. if (this._onDisposeObserver) {
  17809. this.onDisposeObservable.remove(this._onDisposeObserver);
  17810. }
  17811. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17812. },
  17813. enumerable: true,
  17814. configurable: true
  17815. });
  17816. /**
  17817. * Gets the scene of the node
  17818. * @returns a {BABYLON.Scene}
  17819. */
  17820. Node.prototype.getScene = function () {
  17821. return this._scene;
  17822. };
  17823. /**
  17824. * Gets the engine of the node
  17825. * @returns a {BABYLON.Engine}
  17826. */
  17827. Node.prototype.getEngine = function () {
  17828. return this._scene.getEngine();
  17829. };
  17830. /**
  17831. * Attach a behavior to the node
  17832. * @see http://doc.babylonjs.com/features/behaviour
  17833. * @param behavior defines the behavior to attach
  17834. * @returns the current Node
  17835. */
  17836. Node.prototype.addBehavior = function (behavior) {
  17837. var _this = this;
  17838. var index = this._behaviors.indexOf(behavior);
  17839. if (index !== -1) {
  17840. return this;
  17841. }
  17842. behavior.init();
  17843. if (this._scene.isLoading) {
  17844. // We defer the attach when the scene will be loaded
  17845. this._scene.onDataLoadedObservable.addOnce(function () {
  17846. behavior.attach(_this);
  17847. });
  17848. }
  17849. else {
  17850. behavior.attach(this);
  17851. }
  17852. this._behaviors.push(behavior);
  17853. return this;
  17854. };
  17855. /**
  17856. * Remove an attached behavior
  17857. * @see http://doc.babylonjs.com/features/behaviour
  17858. * @param behavior defines the behavior to attach
  17859. * @returns the current Node
  17860. */
  17861. Node.prototype.removeBehavior = function (behavior) {
  17862. var index = this._behaviors.indexOf(behavior);
  17863. if (index === -1) {
  17864. return this;
  17865. }
  17866. this._behaviors[index].detach();
  17867. this._behaviors.splice(index, 1);
  17868. return this;
  17869. };
  17870. Object.defineProperty(Node.prototype, "behaviors", {
  17871. /**
  17872. * Gets the list of attached behaviors
  17873. * @see http://doc.babylonjs.com/features/behaviour
  17874. */
  17875. get: function () {
  17876. return this._behaviors;
  17877. },
  17878. enumerable: true,
  17879. configurable: true
  17880. });
  17881. /**
  17882. * Gets an attached behavior by name
  17883. * @param name defines the name of the behavior to look for
  17884. * @see http://doc.babylonjs.com/features/behaviour
  17885. * @returns null if behavior was not found else the requested behavior
  17886. */
  17887. Node.prototype.getBehaviorByName = function (name) {
  17888. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17889. var behavior = _a[_i];
  17890. if (behavior.name === name) {
  17891. return behavior;
  17892. }
  17893. }
  17894. return null;
  17895. };
  17896. /**
  17897. * Returns the world matrix of the node
  17898. * @returns a matrix containing the node's world matrix
  17899. */
  17900. Node.prototype.getWorldMatrix = function () {
  17901. return BABYLON.Matrix.Identity();
  17902. };
  17903. /** @hidden */
  17904. Node.prototype._getWorldMatrixDeterminant = function () {
  17905. return 1;
  17906. };
  17907. // override it in derived class if you add new variables to the cache
  17908. // and call the parent class method
  17909. /** @hidden */
  17910. Node.prototype._initCache = function () {
  17911. this._cache = {};
  17912. this._cache.parent = undefined;
  17913. };
  17914. /** @hidden */
  17915. Node.prototype.updateCache = function (force) {
  17916. if (!force && this.isSynchronized())
  17917. return;
  17918. this._cache.parent = this.parent;
  17919. this._updateCache();
  17920. };
  17921. // override it in derived class if you add new variables to the cache
  17922. // and call the parent class method if !ignoreParentClass
  17923. /** @hidden */
  17924. Node.prototype._updateCache = function (ignoreParentClass) {
  17925. };
  17926. // override it in derived class if you add new variables to the cache
  17927. /** @hidden */
  17928. Node.prototype._isSynchronized = function () {
  17929. return true;
  17930. };
  17931. /** @hidden */
  17932. Node.prototype._markSyncedWithParent = function () {
  17933. if (this.parent) {
  17934. this._parentRenderId = this.parent._childRenderId;
  17935. }
  17936. };
  17937. /** @hidden */
  17938. Node.prototype.isSynchronizedWithParent = function () {
  17939. if (!this.parent) {
  17940. return true;
  17941. }
  17942. if (this._parentRenderId !== this.parent._childRenderId) {
  17943. return false;
  17944. }
  17945. return this.parent.isSynchronized();
  17946. };
  17947. /** @hidden */
  17948. Node.prototype.isSynchronized = function (updateCache) {
  17949. var check = this.hasNewParent();
  17950. check = check || !this.isSynchronizedWithParent();
  17951. check = check || !this._isSynchronized();
  17952. if (updateCache)
  17953. this.updateCache(true);
  17954. return !check;
  17955. };
  17956. /** @hidden */
  17957. Node.prototype.hasNewParent = function (update) {
  17958. if (this._cache.parent === this.parent)
  17959. return false;
  17960. if (update)
  17961. this._cache.parent = this.parent;
  17962. return true;
  17963. };
  17964. /**
  17965. * Is this node ready to be used/rendered
  17966. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17967. * @return true if the node is ready
  17968. */
  17969. Node.prototype.isReady = function (completeCheck) {
  17970. if (completeCheck === void 0) { completeCheck = false; }
  17971. return this._isReady;
  17972. };
  17973. /**
  17974. * Is this node enabled?
  17975. * 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
  17976. * @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
  17977. * @return whether this node (and its parent) is enabled
  17978. */
  17979. Node.prototype.isEnabled = function (checkAncestors) {
  17980. if (checkAncestors === void 0) { checkAncestors = true; }
  17981. if (checkAncestors === false) {
  17982. return this._isEnabled;
  17983. }
  17984. if (this._isEnabled === false) {
  17985. return false;
  17986. }
  17987. if (this.parent !== undefined && this.parent !== null) {
  17988. return this.parent.isEnabled(checkAncestors);
  17989. }
  17990. return true;
  17991. };
  17992. /**
  17993. * Set the enabled state of this node
  17994. * @param value defines the new enabled state
  17995. */
  17996. Node.prototype.setEnabled = function (value) {
  17997. this._isEnabled = value;
  17998. };
  17999. /**
  18000. * Is this node a descendant of the given node?
  18001. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18002. * @param ancestor defines the parent node to inspect
  18003. * @returns a boolean indicating if this node is a descendant of the given node
  18004. */
  18005. Node.prototype.isDescendantOf = function (ancestor) {
  18006. if (this.parent) {
  18007. if (this.parent === ancestor) {
  18008. return true;
  18009. }
  18010. return this.parent.isDescendantOf(ancestor);
  18011. }
  18012. return false;
  18013. };
  18014. /** @hidden */
  18015. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18016. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18017. if (!this._children) {
  18018. return;
  18019. }
  18020. for (var index = 0; index < this._children.length; index++) {
  18021. var item = this._children[index];
  18022. if (!predicate || predicate(item)) {
  18023. results.push(item);
  18024. }
  18025. if (!directDescendantsOnly) {
  18026. item._getDescendants(results, false, predicate);
  18027. }
  18028. }
  18029. };
  18030. /**
  18031. * Will return all nodes that have this node as ascendant
  18032. * @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
  18033. * @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
  18034. * @return all children nodes of all types
  18035. */
  18036. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18037. var results = new Array();
  18038. this._getDescendants(results, directDescendantsOnly, predicate);
  18039. return results;
  18040. };
  18041. /**
  18042. * Get all child-meshes of this node
  18043. * @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
  18044. * @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
  18045. * @returns an array of {BABYLON.AbstractMesh}
  18046. */
  18047. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18048. var results = [];
  18049. this._getDescendants(results, directDescendantsOnly, function (node) {
  18050. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18051. });
  18052. return results;
  18053. };
  18054. /**
  18055. * Get all child-transformNodes of this node
  18056. * @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
  18057. * @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
  18058. * @returns an array of {BABYLON.TransformNode}
  18059. */
  18060. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18061. var results = [];
  18062. this._getDescendants(results, directDescendantsOnly, function (node) {
  18063. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18064. });
  18065. return results;
  18066. };
  18067. /**
  18068. * Get all direct children of this node
  18069. * @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
  18070. * @returns an array of {BABYLON.Node}
  18071. */
  18072. Node.prototype.getChildren = function (predicate) {
  18073. return this.getDescendants(true, predicate);
  18074. };
  18075. /** @hidden */
  18076. Node.prototype._setReady = function (state) {
  18077. if (state === this._isReady) {
  18078. return;
  18079. }
  18080. if (!state) {
  18081. this._isReady = false;
  18082. return;
  18083. }
  18084. if (this.onReady) {
  18085. this.onReady(this);
  18086. }
  18087. this._isReady = true;
  18088. };
  18089. /**
  18090. * Get an animation by name
  18091. * @param name defines the name of the animation to look for
  18092. * @returns null if not found else the requested animation
  18093. */
  18094. Node.prototype.getAnimationByName = function (name) {
  18095. for (var i = 0; i < this.animations.length; i++) {
  18096. var animation = this.animations[i];
  18097. if (animation.name === name) {
  18098. return animation;
  18099. }
  18100. }
  18101. return null;
  18102. };
  18103. /**
  18104. * Creates an animation range for this node
  18105. * @param name defines the name of the range
  18106. * @param from defines the starting key
  18107. * @param to defines the end key
  18108. */
  18109. Node.prototype.createAnimationRange = function (name, from, to) {
  18110. // check name not already in use
  18111. if (!this._ranges[name]) {
  18112. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18113. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18114. if (this.animations[i]) {
  18115. this.animations[i].createRange(name, from, to);
  18116. }
  18117. }
  18118. }
  18119. };
  18120. /**
  18121. * Delete a specific animation range
  18122. * @param name defines the name of the range to delete
  18123. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18124. */
  18125. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18126. if (deleteFrames === void 0) { deleteFrames = true; }
  18127. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18128. if (this.animations[i]) {
  18129. this.animations[i].deleteRange(name, deleteFrames);
  18130. }
  18131. }
  18132. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18133. };
  18134. /**
  18135. * Get an animation range by name
  18136. * @param name defines the name of the animation range to look for
  18137. * @returns null if not found else the requested animation range
  18138. */
  18139. Node.prototype.getAnimationRange = function (name) {
  18140. return this._ranges[name];
  18141. };
  18142. /**
  18143. * Will start the animation sequence
  18144. * @param name defines the range frames for animation sequence
  18145. * @param loop defines if the animation should loop (false by default)
  18146. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18147. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18148. * @returns the object created for this animation. If range does not exist, it will return null
  18149. */
  18150. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18151. var range = this.getAnimationRange(name);
  18152. if (!range) {
  18153. return null;
  18154. }
  18155. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18156. };
  18157. /**
  18158. * Serialize animation ranges into a JSON compatible object
  18159. * @returns serialization object
  18160. */
  18161. Node.prototype.serializeAnimationRanges = function () {
  18162. var serializationRanges = [];
  18163. for (var name in this._ranges) {
  18164. var localRange = this._ranges[name];
  18165. if (!localRange) {
  18166. continue;
  18167. }
  18168. var range = {};
  18169. range.name = name;
  18170. range.from = localRange.from;
  18171. range.to = localRange.to;
  18172. serializationRanges.push(range);
  18173. }
  18174. return serializationRanges;
  18175. };
  18176. /**
  18177. * Computes the world matrix of the node
  18178. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18179. * @returns the world matrix
  18180. */
  18181. Node.prototype.computeWorldMatrix = function (force) {
  18182. return BABYLON.Matrix.Identity();
  18183. };
  18184. /**
  18185. * Releases resources associated with this node.
  18186. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18187. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18188. */
  18189. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18190. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18191. if (!doNotRecurse) {
  18192. var nodes = this.getDescendants(true);
  18193. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18194. var node = nodes_1[_i];
  18195. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18196. }
  18197. }
  18198. else {
  18199. var transformNodes = this.getChildTransformNodes(true);
  18200. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18201. var transformNode = transformNodes_1[_a];
  18202. transformNode.parent = null;
  18203. transformNode.computeWorldMatrix(true);
  18204. }
  18205. }
  18206. this.parent = null;
  18207. // Callback
  18208. this.onDisposeObservable.notifyObservers(this);
  18209. this.onDisposeObservable.clear();
  18210. // Behaviors
  18211. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18212. var behavior = _c[_b];
  18213. behavior.detach();
  18214. }
  18215. this._behaviors = [];
  18216. this._isDisposed = true;
  18217. };
  18218. /**
  18219. * Parse animation range data from a serialization object and store them into a given node
  18220. * @param node defines where to store the animation ranges
  18221. * @param parsedNode defines the serialization object to read data from
  18222. * @param scene defines the hosting scene
  18223. */
  18224. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18225. if (parsedNode.ranges) {
  18226. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18227. var data = parsedNode.ranges[index];
  18228. node.createAnimationRange(data.name, data.from, data.to);
  18229. }
  18230. }
  18231. };
  18232. __decorate([
  18233. BABYLON.serialize()
  18234. ], Node.prototype, "name", void 0);
  18235. __decorate([
  18236. BABYLON.serialize()
  18237. ], Node.prototype, "id", void 0);
  18238. __decorate([
  18239. BABYLON.serialize()
  18240. ], Node.prototype, "uniqueId", void 0);
  18241. __decorate([
  18242. BABYLON.serialize()
  18243. ], Node.prototype, "state", void 0);
  18244. __decorate([
  18245. BABYLON.serialize()
  18246. ], Node.prototype, "metadata", void 0);
  18247. return Node;
  18248. }());
  18249. BABYLON.Node = Node;
  18250. })(BABYLON || (BABYLON = {}));
  18251. //# sourceMappingURL=babylon.node.js.map
  18252. var BABYLON;
  18253. (function (BABYLON) {
  18254. var BoundingSphere = /** @class */ (function () {
  18255. /**
  18256. * Creates a new bounding sphere
  18257. * @param min defines the minimum vector (in local space)
  18258. * @param max defines the maximum vector (in local space)
  18259. */
  18260. function BoundingSphere(min, max) {
  18261. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18262. this.reConstruct(min, max);
  18263. }
  18264. /**
  18265. * Recreates the entire bounding sphere from scratch
  18266. * @param min defines the new minimum vector (in local space)
  18267. * @param max defines the new maximum vector (in local space)
  18268. */
  18269. BoundingSphere.prototype.reConstruct = function (min, max) {
  18270. this.minimum = min.clone();
  18271. this.maximum = max.clone();
  18272. var distance = BABYLON.Vector3.Distance(min, max);
  18273. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18274. this.radius = distance * 0.5;
  18275. this.centerWorld = BABYLON.Vector3.Zero();
  18276. this._update(BABYLON.Matrix.Identity());
  18277. };
  18278. // Methods
  18279. BoundingSphere.prototype._update = function (world) {
  18280. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18281. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18282. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18283. };
  18284. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18285. for (var i = 0; i < 6; i++) {
  18286. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18287. return false;
  18288. }
  18289. return true;
  18290. };
  18291. BoundingSphere.prototype.intersectsPoint = function (point) {
  18292. var x = this.centerWorld.x - point.x;
  18293. var y = this.centerWorld.y - point.y;
  18294. var z = this.centerWorld.z - point.z;
  18295. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18296. if (this.radiusWorld < distance)
  18297. return false;
  18298. return true;
  18299. };
  18300. // Statics
  18301. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18302. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18303. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18304. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18305. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18306. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18307. return false;
  18308. return true;
  18309. };
  18310. return BoundingSphere;
  18311. }());
  18312. BABYLON.BoundingSphere = BoundingSphere;
  18313. })(BABYLON || (BABYLON = {}));
  18314. //# sourceMappingURL=babylon.boundingSphere.js.map
  18315. var BABYLON;
  18316. (function (BABYLON) {
  18317. var BoundingBox = /** @class */ (function () {
  18318. /**
  18319. * Creates a new bounding box
  18320. * @param min defines the minimum vector (in local space)
  18321. * @param max defines the maximum vector (in local space)
  18322. */
  18323. function BoundingBox(min, max) {
  18324. this.vectorsWorld = new Array();
  18325. this.reConstruct(min, max);
  18326. }
  18327. // Methods
  18328. /**
  18329. * Recreates the entire bounding box from scratch
  18330. * @param min defines the new minimum vector (in local space)
  18331. * @param max defines the new maximum vector (in local space)
  18332. */
  18333. BoundingBox.prototype.reConstruct = function (min, max) {
  18334. this.minimum = min.clone();
  18335. this.maximum = max.clone();
  18336. // Bounding vectors
  18337. this.vectors = new Array();
  18338. this.vectors.push(this.minimum.clone());
  18339. this.vectors.push(this.maximum.clone());
  18340. this.vectors.push(this.minimum.clone());
  18341. this.vectors[2].x = this.maximum.x;
  18342. this.vectors.push(this.minimum.clone());
  18343. this.vectors[3].y = this.maximum.y;
  18344. this.vectors.push(this.minimum.clone());
  18345. this.vectors[4].z = this.maximum.z;
  18346. this.vectors.push(this.maximum.clone());
  18347. this.vectors[5].z = this.minimum.z;
  18348. this.vectors.push(this.maximum.clone());
  18349. this.vectors[6].x = this.minimum.x;
  18350. this.vectors.push(this.maximum.clone());
  18351. this.vectors[7].y = this.minimum.y;
  18352. // OBB
  18353. this.center = this.maximum.add(this.minimum).scale(0.5);
  18354. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18355. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18356. // World
  18357. for (var index = 0; index < this.vectors.length; index++) {
  18358. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18359. }
  18360. this.minimumWorld = BABYLON.Vector3.Zero();
  18361. this.maximumWorld = BABYLON.Vector3.Zero();
  18362. this.centerWorld = BABYLON.Vector3.Zero();
  18363. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18364. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18365. };
  18366. BoundingBox.prototype.getWorldMatrix = function () {
  18367. return this._worldMatrix;
  18368. };
  18369. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18370. this._worldMatrix.copyFrom(matrix);
  18371. return this;
  18372. };
  18373. BoundingBox.prototype._update = function (world) {
  18374. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18375. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18376. for (var index = 0; index < this.vectors.length; index++) {
  18377. var v = this.vectorsWorld[index];
  18378. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18379. if (v.x < this.minimumWorld.x)
  18380. this.minimumWorld.x = v.x;
  18381. if (v.y < this.minimumWorld.y)
  18382. this.minimumWorld.y = v.y;
  18383. if (v.z < this.minimumWorld.z)
  18384. this.minimumWorld.z = v.z;
  18385. if (v.x > this.maximumWorld.x)
  18386. this.maximumWorld.x = v.x;
  18387. if (v.y > this.maximumWorld.y)
  18388. this.maximumWorld.y = v.y;
  18389. if (v.z > this.maximumWorld.z)
  18390. this.maximumWorld.z = v.z;
  18391. }
  18392. // Extend
  18393. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18394. this.extendSizeWorld.scaleInPlace(0.5);
  18395. // OBB
  18396. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18397. this.centerWorld.scaleInPlace(0.5);
  18398. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18399. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18400. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18401. this._worldMatrix = world;
  18402. };
  18403. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18404. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18405. };
  18406. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18407. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18408. };
  18409. BoundingBox.prototype.intersectsPoint = function (point) {
  18410. var delta = -BABYLON.Epsilon;
  18411. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18412. return false;
  18413. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18414. return false;
  18415. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18416. return false;
  18417. return true;
  18418. };
  18419. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18420. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18421. };
  18422. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18423. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18424. return false;
  18425. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18426. return false;
  18427. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18428. return false;
  18429. return true;
  18430. };
  18431. // Statics
  18432. BoundingBox.Intersects = function (box0, box1) {
  18433. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18434. return false;
  18435. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18436. return false;
  18437. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18438. return false;
  18439. return true;
  18440. };
  18441. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18442. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18443. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18444. return (num <= (sphereRadius * sphereRadius));
  18445. };
  18446. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18447. for (var p = 0; p < 6; p++) {
  18448. for (var i = 0; i < 8; i++) {
  18449. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18450. return false;
  18451. }
  18452. }
  18453. }
  18454. return true;
  18455. };
  18456. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18457. for (var p = 0; p < 6; p++) {
  18458. var inCount = 8;
  18459. for (var i = 0; i < 8; i++) {
  18460. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18461. --inCount;
  18462. }
  18463. else {
  18464. break;
  18465. }
  18466. }
  18467. if (inCount === 0)
  18468. return false;
  18469. }
  18470. return true;
  18471. };
  18472. return BoundingBox;
  18473. }());
  18474. BABYLON.BoundingBox = BoundingBox;
  18475. })(BABYLON || (BABYLON = {}));
  18476. //# sourceMappingURL=babylon.boundingBox.js.map
  18477. var BABYLON;
  18478. (function (BABYLON) {
  18479. var computeBoxExtents = function (axis, box) {
  18480. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18481. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18482. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18483. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18484. var r = r0 + r1 + r2;
  18485. return {
  18486. min: p - r,
  18487. max: p + r
  18488. };
  18489. };
  18490. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18491. var axisOverlap = function (axis, box0, box1) {
  18492. var result0 = computeBoxExtents(axis, box0);
  18493. var result1 = computeBoxExtents(axis, box1);
  18494. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18495. };
  18496. var BoundingInfo = /** @class */ (function () {
  18497. function BoundingInfo(minimum, maximum) {
  18498. this.minimum = minimum;
  18499. this.maximum = maximum;
  18500. this._isLocked = false;
  18501. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18502. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18503. }
  18504. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18505. get: function () {
  18506. return this._isLocked;
  18507. },
  18508. set: function (value) {
  18509. this._isLocked = value;
  18510. },
  18511. enumerable: true,
  18512. configurable: true
  18513. });
  18514. // Methods
  18515. BoundingInfo.prototype.update = function (world) {
  18516. if (this._isLocked) {
  18517. return;
  18518. }
  18519. this.boundingBox._update(world);
  18520. this.boundingSphere._update(world);
  18521. };
  18522. /**
  18523. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18524. * @param center New center of the bounding info
  18525. * @param extend New extend of the bounding info
  18526. */
  18527. BoundingInfo.prototype.centerOn = function (center, extend) {
  18528. this.minimum = center.subtract(extend);
  18529. this.maximum = center.add(extend);
  18530. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18531. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18532. return this;
  18533. };
  18534. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18535. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18536. return false;
  18537. return this.boundingBox.isInFrustum(frustumPlanes);
  18538. };
  18539. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18540. /**
  18541. * Gets the world distance between the min and max points of the bounding box
  18542. */
  18543. get: function () {
  18544. var boundingBox = this.boundingBox;
  18545. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18546. return size.length();
  18547. },
  18548. enumerable: true,
  18549. configurable: true
  18550. });
  18551. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18552. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18553. };
  18554. BoundingInfo.prototype._checkCollision = function (collider) {
  18555. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18556. };
  18557. BoundingInfo.prototype.intersectsPoint = function (point) {
  18558. if (!this.boundingSphere.centerWorld) {
  18559. return false;
  18560. }
  18561. if (!this.boundingSphere.intersectsPoint(point)) {
  18562. return false;
  18563. }
  18564. if (!this.boundingBox.intersectsPoint(point)) {
  18565. return false;
  18566. }
  18567. return true;
  18568. };
  18569. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18570. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18571. return false;
  18572. }
  18573. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18574. return false;
  18575. }
  18576. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18577. return false;
  18578. }
  18579. if (!precise) {
  18580. return true;
  18581. }
  18582. var box0 = this.boundingBox;
  18583. var box1 = boundingInfo.boundingBox;
  18584. if (!axisOverlap(box0.directions[0], box0, box1))
  18585. return false;
  18586. if (!axisOverlap(box0.directions[1], box0, box1))
  18587. return false;
  18588. if (!axisOverlap(box0.directions[2], box0, box1))
  18589. return false;
  18590. if (!axisOverlap(box1.directions[0], box0, box1))
  18591. return false;
  18592. if (!axisOverlap(box1.directions[1], box0, box1))
  18593. return false;
  18594. if (!axisOverlap(box1.directions[2], box0, box1))
  18595. return false;
  18596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18597. return false;
  18598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18599. return false;
  18600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18601. return false;
  18602. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18603. return false;
  18604. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18605. return false;
  18606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18607. return false;
  18608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18609. return false;
  18610. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18611. return false;
  18612. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18613. return false;
  18614. return true;
  18615. };
  18616. return BoundingInfo;
  18617. }());
  18618. BABYLON.BoundingInfo = BoundingInfo;
  18619. })(BABYLON || (BABYLON = {}));
  18620. //# sourceMappingURL=babylon.boundingInfo.js.map
  18621. var BABYLON;
  18622. (function (BABYLON) {
  18623. var TransformNode = /** @class */ (function (_super) {
  18624. __extends(TransformNode, _super);
  18625. function TransformNode(name, scene, isPure) {
  18626. if (scene === void 0) { scene = null; }
  18627. if (isPure === void 0) { isPure = true; }
  18628. var _this = _super.call(this, name, scene) || this;
  18629. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18630. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18631. _this._up = new BABYLON.Vector3(0, 1, 0);
  18632. _this._right = new BABYLON.Vector3(1, 0, 0);
  18633. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18634. // Properties
  18635. _this._rotation = BABYLON.Vector3.Zero();
  18636. _this._scaling = BABYLON.Vector3.One();
  18637. _this._isDirty = false;
  18638. /**
  18639. * Set the billboard mode. Default is 0.
  18640. *
  18641. * | Value | Type | Description |
  18642. * | --- | --- | --- |
  18643. * | 0 | BILLBOARDMODE_NONE | |
  18644. * | 1 | BILLBOARDMODE_X | |
  18645. * | 2 | BILLBOARDMODE_Y | |
  18646. * | 4 | BILLBOARDMODE_Z | |
  18647. * | 7 | BILLBOARDMODE_ALL | |
  18648. *
  18649. */
  18650. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18651. _this.scalingDeterminant = 1;
  18652. _this.infiniteDistance = false;
  18653. /**
  18654. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18655. * By default the system will update normals to compensate
  18656. */
  18657. _this.ignoreNonUniformScaling = false;
  18658. _this.position = BABYLON.Vector3.Zero();
  18659. _this._localWorld = BABYLON.Matrix.Zero();
  18660. _this._worldMatrix = BABYLON.Matrix.Zero();
  18661. _this._worldMatrixDeterminant = 0;
  18662. _this._absolutePosition = BABYLON.Vector3.Zero();
  18663. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18664. _this._postMultiplyPivotMatrix = false;
  18665. _this._isWorldMatrixFrozen = false;
  18666. /**
  18667. * An event triggered after the world matrix is updated
  18668. */
  18669. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18670. _this._nonUniformScaling = false;
  18671. if (isPure) {
  18672. _this.getScene().addTransformNode(_this);
  18673. }
  18674. return _this;
  18675. }
  18676. /**
  18677. * Gets a string idenfifying the name of the class
  18678. * @returns "TransformNode" string
  18679. */
  18680. TransformNode.prototype.getClassName = function () {
  18681. return "TransformNode";
  18682. };
  18683. Object.defineProperty(TransformNode.prototype, "rotation", {
  18684. /**
  18685. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18686. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18687. * Default : (0.0, 0.0, 0.0)
  18688. */
  18689. get: function () {
  18690. return this._rotation;
  18691. },
  18692. set: function (newRotation) {
  18693. this._rotation = newRotation;
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. Object.defineProperty(TransformNode.prototype, "scaling", {
  18699. /**
  18700. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18701. * Default : (1.0, 1.0, 1.0)
  18702. */
  18703. get: function () {
  18704. return this._scaling;
  18705. },
  18706. /**
  18707. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18708. * Default : (1.0, 1.0, 1.0)
  18709. */
  18710. set: function (newScaling) {
  18711. this._scaling = newScaling;
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18717. /**
  18718. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18719. * It's null by default.
  18720. * 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)
  18721. */
  18722. get: function () {
  18723. return this._rotationQuaternion;
  18724. },
  18725. set: function (quaternion) {
  18726. this._rotationQuaternion = quaternion;
  18727. //reset the rotation vector.
  18728. if (quaternion && this.rotation.length()) {
  18729. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18730. }
  18731. },
  18732. enumerable: true,
  18733. configurable: true
  18734. });
  18735. Object.defineProperty(TransformNode.prototype, "forward", {
  18736. /**
  18737. * The forward direction of that transform in world space.
  18738. */
  18739. get: function () {
  18740. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. Object.defineProperty(TransformNode.prototype, "up", {
  18746. /**
  18747. * The up direction of that transform in world space.
  18748. */
  18749. get: function () {
  18750. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18751. },
  18752. enumerable: true,
  18753. configurable: true
  18754. });
  18755. Object.defineProperty(TransformNode.prototype, "right", {
  18756. /**
  18757. * The right direction of that transform in world space.
  18758. */
  18759. get: function () {
  18760. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. /**
  18766. * Returns the latest update of the World matrix
  18767. * Returns a Matrix.
  18768. */
  18769. TransformNode.prototype.getWorldMatrix = function () {
  18770. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18771. this.computeWorldMatrix();
  18772. }
  18773. return this._worldMatrix;
  18774. };
  18775. /** @hidden */
  18776. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18777. return this._worldMatrixDeterminant;
  18778. };
  18779. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18780. /**
  18781. * Returns directly the latest state of the mesh World matrix.
  18782. * A Matrix is returned.
  18783. */
  18784. get: function () {
  18785. return this._worldMatrix;
  18786. },
  18787. enumerable: true,
  18788. configurable: true
  18789. });
  18790. /**
  18791. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18792. * Returns the TransformNode.
  18793. */
  18794. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18795. this._poseMatrix.copyFrom(matrix);
  18796. return this;
  18797. };
  18798. /**
  18799. * Returns the mesh Pose matrix.
  18800. * Returned object : Matrix
  18801. */
  18802. TransformNode.prototype.getPoseMatrix = function () {
  18803. return this._poseMatrix;
  18804. };
  18805. TransformNode.prototype._isSynchronized = function () {
  18806. if (this._isDirty) {
  18807. return false;
  18808. }
  18809. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18810. return false;
  18811. if (this._cache.pivotMatrixUpdated) {
  18812. return false;
  18813. }
  18814. if (this.infiniteDistance) {
  18815. return false;
  18816. }
  18817. if (!this._cache.position.equals(this.position))
  18818. return false;
  18819. if (this.rotationQuaternion) {
  18820. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18821. return false;
  18822. }
  18823. if (!this._cache.rotation.equals(this.rotation))
  18824. return false;
  18825. if (!this._cache.scaling.equals(this.scaling))
  18826. return false;
  18827. return true;
  18828. };
  18829. TransformNode.prototype._initCache = function () {
  18830. _super.prototype._initCache.call(this);
  18831. this._cache.localMatrixUpdated = false;
  18832. this._cache.position = BABYLON.Vector3.Zero();
  18833. this._cache.scaling = BABYLON.Vector3.Zero();
  18834. this._cache.rotation = BABYLON.Vector3.Zero();
  18835. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18836. this._cache.billboardMode = -1;
  18837. };
  18838. TransformNode.prototype.markAsDirty = function (property) {
  18839. if (property === "rotation") {
  18840. this.rotationQuaternion = null;
  18841. }
  18842. this._currentRenderId = Number.MAX_VALUE;
  18843. this._isDirty = true;
  18844. return this;
  18845. };
  18846. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18847. /**
  18848. * Returns the current mesh absolute position.
  18849. * Retuns a Vector3.
  18850. */
  18851. get: function () {
  18852. return this._absolutePosition;
  18853. },
  18854. enumerable: true,
  18855. configurable: true
  18856. });
  18857. /**
  18858. * Sets a new matrix to apply before all other transformation
  18859. * @param matrix defines the transform matrix
  18860. * @returns the current TransformNode
  18861. */
  18862. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18863. return this.setPivotMatrix(matrix, false);
  18864. };
  18865. /**
  18866. * Sets a new pivot matrix to the current node
  18867. * @param matrix defines the new pivot matrix to use
  18868. * @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
  18869. * @returns the current TransformNode
  18870. */
  18871. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18872. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18873. this._pivotMatrix = matrix.clone();
  18874. this._cache.pivotMatrixUpdated = true;
  18875. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18876. if (this._postMultiplyPivotMatrix) {
  18877. if (!this._pivotMatrixInverse) {
  18878. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18879. }
  18880. else {
  18881. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18882. }
  18883. }
  18884. return this;
  18885. };
  18886. /**
  18887. * Returns the mesh pivot matrix.
  18888. * Default : Identity.
  18889. * A Matrix is returned.
  18890. */
  18891. TransformNode.prototype.getPivotMatrix = function () {
  18892. return this._pivotMatrix;
  18893. };
  18894. /**
  18895. * Prevents the World matrix to be computed any longer.
  18896. * Returns the TransformNode.
  18897. */
  18898. TransformNode.prototype.freezeWorldMatrix = function () {
  18899. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18900. this.computeWorldMatrix(true);
  18901. this._isWorldMatrixFrozen = true;
  18902. return this;
  18903. };
  18904. /**
  18905. * Allows back the World matrix computation.
  18906. * Returns the TransformNode.
  18907. */
  18908. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18909. this._isWorldMatrixFrozen = false;
  18910. this.computeWorldMatrix(true);
  18911. return this;
  18912. };
  18913. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18914. /**
  18915. * True if the World matrix has been frozen.
  18916. * Returns a boolean.
  18917. */
  18918. get: function () {
  18919. return this._isWorldMatrixFrozen;
  18920. },
  18921. enumerable: true,
  18922. configurable: true
  18923. });
  18924. /**
  18925. * Retuns the mesh absolute position in the World.
  18926. * Returns a Vector3.
  18927. */
  18928. TransformNode.prototype.getAbsolutePosition = function () {
  18929. this.computeWorldMatrix();
  18930. return this._absolutePosition;
  18931. };
  18932. /**
  18933. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18934. * Returns the TransformNode.
  18935. */
  18936. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18937. if (!absolutePosition) {
  18938. return this;
  18939. }
  18940. var absolutePositionX;
  18941. var absolutePositionY;
  18942. var absolutePositionZ;
  18943. if (absolutePosition.x === undefined) {
  18944. if (arguments.length < 3) {
  18945. return this;
  18946. }
  18947. absolutePositionX = arguments[0];
  18948. absolutePositionY = arguments[1];
  18949. absolutePositionZ = arguments[2];
  18950. }
  18951. else {
  18952. absolutePositionX = absolutePosition.x;
  18953. absolutePositionY = absolutePosition.y;
  18954. absolutePositionZ = absolutePosition.z;
  18955. }
  18956. if (this.parent) {
  18957. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18958. invertParentWorldMatrix.invert();
  18959. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18960. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18961. }
  18962. else {
  18963. this.position.x = absolutePositionX;
  18964. this.position.y = absolutePositionY;
  18965. this.position.z = absolutePositionZ;
  18966. }
  18967. return this;
  18968. };
  18969. /**
  18970. * Sets the mesh position in its local space.
  18971. * Returns the TransformNode.
  18972. */
  18973. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18974. this.computeWorldMatrix();
  18975. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18976. return this;
  18977. };
  18978. /**
  18979. * Returns the mesh position in the local space from the current World matrix values.
  18980. * Returns a new Vector3.
  18981. */
  18982. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18983. this.computeWorldMatrix();
  18984. var invLocalWorldMatrix = this._localWorld.clone();
  18985. invLocalWorldMatrix.invert();
  18986. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18987. };
  18988. /**
  18989. * Translates the mesh along the passed Vector3 in its local space.
  18990. * Returns the TransformNode.
  18991. */
  18992. TransformNode.prototype.locallyTranslate = function (vector3) {
  18993. this.computeWorldMatrix(true);
  18994. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18995. return this;
  18996. };
  18997. /**
  18998. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18999. * @param targetPoint the position (must be in same space as current mesh) to look at
  19000. * @param yawCor optional yaw (y-axis) correction in radians
  19001. * @param pitchCor optional pitch (x-axis) correction in radians
  19002. * @param rollCor optional roll (z-axis) correction in radians
  19003. * @param space the choosen space of the target
  19004. * @returns the TransformNode.
  19005. */
  19006. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19007. if (yawCor === void 0) { yawCor = 0; }
  19008. if (pitchCor === void 0) { pitchCor = 0; }
  19009. if (rollCor === void 0) { rollCor = 0; }
  19010. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19011. var dv = TransformNode._lookAtVectorCache;
  19012. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19013. targetPoint.subtractToRef(pos, dv);
  19014. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19015. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19016. var pitch = Math.atan2(dv.y, len);
  19017. if (this.rotationQuaternion) {
  19018. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19019. }
  19020. else {
  19021. this.rotation.x = pitch + pitchCor;
  19022. this.rotation.y = yaw + yawCor;
  19023. this.rotation.z = rollCor;
  19024. }
  19025. return this;
  19026. };
  19027. /**
  19028. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19029. * This Vector3 is expressed in the World space.
  19030. */
  19031. TransformNode.prototype.getDirection = function (localAxis) {
  19032. var result = BABYLON.Vector3.Zero();
  19033. this.getDirectionToRef(localAxis, result);
  19034. return result;
  19035. };
  19036. /**
  19037. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19038. * localAxis is expressed in the mesh local space.
  19039. * result is computed in the Wordl space from the mesh World matrix.
  19040. * Returns the TransformNode.
  19041. */
  19042. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19043. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19044. return this;
  19045. };
  19046. /**
  19047. * Sets a new pivot point to the current node
  19048. * @param point defines the new pivot point to use
  19049. * @param space defines if the point is in world or local space (local by default)
  19050. * @returns the current TransformNode
  19051. */
  19052. TransformNode.prototype.setPivotPoint = function (point, space) {
  19053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19054. if (this.getScene().getRenderId() == 0) {
  19055. this.computeWorldMatrix(true);
  19056. }
  19057. var wm = this.getWorldMatrix();
  19058. if (space == BABYLON.Space.WORLD) {
  19059. var tmat = BABYLON.Tmp.Matrix[0];
  19060. wm.invertToRef(tmat);
  19061. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19062. }
  19063. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19064. };
  19065. /**
  19066. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19067. */
  19068. TransformNode.prototype.getPivotPoint = function () {
  19069. var point = BABYLON.Vector3.Zero();
  19070. this.getPivotPointToRef(point);
  19071. return point;
  19072. };
  19073. /**
  19074. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19075. * Returns the TransformNode.
  19076. */
  19077. TransformNode.prototype.getPivotPointToRef = function (result) {
  19078. result.x = -this._pivotMatrix.m[12];
  19079. result.y = -this._pivotMatrix.m[13];
  19080. result.z = -this._pivotMatrix.m[14];
  19081. return this;
  19082. };
  19083. /**
  19084. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19085. */
  19086. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19087. var point = BABYLON.Vector3.Zero();
  19088. this.getAbsolutePivotPointToRef(point);
  19089. return point;
  19090. };
  19091. /**
  19092. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19093. * Returns the TransformNode.
  19094. */
  19095. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19096. result.x = this._pivotMatrix.m[12];
  19097. result.y = this._pivotMatrix.m[13];
  19098. result.z = this._pivotMatrix.m[14];
  19099. this.getPivotPointToRef(result);
  19100. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19101. return this;
  19102. };
  19103. /**
  19104. * Defines the passed node as the parent of the current node.
  19105. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19106. * Returns the TransformNode.
  19107. */
  19108. TransformNode.prototype.setParent = function (node) {
  19109. if (!node && !this.parent) {
  19110. return this;
  19111. }
  19112. if (!node) {
  19113. var rotation = BABYLON.Tmp.Quaternion[0];
  19114. var position = BABYLON.Tmp.Vector3[0];
  19115. var scale = BABYLON.Tmp.Vector3[1];
  19116. if (this.parent && this.parent.computeWorldMatrix) {
  19117. this.parent.computeWorldMatrix(true);
  19118. }
  19119. this.computeWorldMatrix(true);
  19120. this.getWorldMatrix().decompose(scale, rotation, position);
  19121. if (this.rotationQuaternion) {
  19122. this.rotationQuaternion.copyFrom(rotation);
  19123. }
  19124. else {
  19125. rotation.toEulerAnglesToRef(this.rotation);
  19126. }
  19127. this.scaling.x = scale.x;
  19128. this.scaling.y = scale.y;
  19129. this.scaling.z = scale.z;
  19130. this.position.x = position.x;
  19131. this.position.y = position.y;
  19132. this.position.z = position.z;
  19133. }
  19134. else {
  19135. var rotation = BABYLON.Tmp.Quaternion[0];
  19136. var position = BABYLON.Tmp.Vector3[0];
  19137. var scale = BABYLON.Tmp.Vector3[1];
  19138. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19139. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19140. this.computeWorldMatrix(true);
  19141. node.computeWorldMatrix(true);
  19142. node.getWorldMatrix().invertToRef(invParentMatrix);
  19143. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19144. diffMatrix.decompose(scale, rotation, position);
  19145. if (this.rotationQuaternion) {
  19146. this.rotationQuaternion.copyFrom(rotation);
  19147. }
  19148. else {
  19149. rotation.toEulerAnglesToRef(this.rotation);
  19150. }
  19151. this.position.x = position.x;
  19152. this.position.y = position.y;
  19153. this.position.z = position.z;
  19154. this.scaling.x = scale.x;
  19155. this.scaling.y = scale.y;
  19156. this.scaling.z = scale.z;
  19157. }
  19158. this.parent = node;
  19159. return this;
  19160. };
  19161. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19162. get: function () {
  19163. return this._nonUniformScaling;
  19164. },
  19165. enumerable: true,
  19166. configurable: true
  19167. });
  19168. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19169. if (this._nonUniformScaling === value) {
  19170. return false;
  19171. }
  19172. this._nonUniformScaling = value;
  19173. return true;
  19174. };
  19175. /**
  19176. * Attach the current TransformNode to another TransformNode associated with a bone
  19177. * @param bone Bone affecting the TransformNode
  19178. * @param affectedTransformNode TransformNode associated with the bone
  19179. */
  19180. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19181. this._transformToBoneReferal = affectedTransformNode;
  19182. this.parent = bone;
  19183. if (bone.getWorldMatrix().determinant() < 0) {
  19184. this.scalingDeterminant *= -1;
  19185. }
  19186. return this;
  19187. };
  19188. TransformNode.prototype.detachFromBone = function () {
  19189. if (!this.parent) {
  19190. return this;
  19191. }
  19192. if (this.parent.getWorldMatrix().determinant() < 0) {
  19193. this.scalingDeterminant *= -1;
  19194. }
  19195. this._transformToBoneReferal = null;
  19196. this.parent = null;
  19197. return this;
  19198. };
  19199. /**
  19200. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19201. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19202. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19203. * The passed axis is also normalized.
  19204. * Returns the TransformNode.
  19205. */
  19206. TransformNode.prototype.rotate = function (axis, amount, space) {
  19207. axis.normalize();
  19208. if (!this.rotationQuaternion) {
  19209. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19210. this.rotation = BABYLON.Vector3.Zero();
  19211. }
  19212. var rotationQuaternion;
  19213. if (!space || space === BABYLON.Space.LOCAL) {
  19214. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19215. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19216. }
  19217. else {
  19218. if (this.parent) {
  19219. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19220. invertParentWorldMatrix.invert();
  19221. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19222. }
  19223. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19224. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19225. }
  19226. return this;
  19227. };
  19228. /**
  19229. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19230. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19231. * The passed axis is also normalized.
  19232. * Returns the TransformNode.
  19233. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19234. */
  19235. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19236. axis.normalize();
  19237. if (!this.rotationQuaternion) {
  19238. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19239. this.rotation.copyFromFloats(0, 0, 0);
  19240. }
  19241. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19242. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19243. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19244. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19245. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19246. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19247. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19248. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19249. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19250. return this;
  19251. };
  19252. /**
  19253. * Translates the mesh along the axis vector for the passed distance in the given space.
  19254. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19255. * Returns the TransformNode.
  19256. */
  19257. TransformNode.prototype.translate = function (axis, distance, space) {
  19258. var displacementVector = axis.scale(distance);
  19259. if (!space || space === BABYLON.Space.LOCAL) {
  19260. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19261. this.setPositionWithLocalVector(tempV3);
  19262. }
  19263. else {
  19264. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19265. }
  19266. return this;
  19267. };
  19268. /**
  19269. * Adds a rotation step to the mesh current rotation.
  19270. * x, y, z are Euler angles expressed in radians.
  19271. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19272. * This means this rotation is made in the mesh local space only.
  19273. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19274. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19275. * ```javascript
  19276. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19277. * ```
  19278. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19279. * 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.
  19280. * Returns the TransformNode.
  19281. */
  19282. TransformNode.prototype.addRotation = function (x, y, z) {
  19283. var rotationQuaternion;
  19284. if (this.rotationQuaternion) {
  19285. rotationQuaternion = this.rotationQuaternion;
  19286. }
  19287. else {
  19288. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19289. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19290. }
  19291. var accumulation = BABYLON.Tmp.Quaternion[0];
  19292. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19293. rotationQuaternion.multiplyInPlace(accumulation);
  19294. if (!this.rotationQuaternion) {
  19295. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19296. }
  19297. return this;
  19298. };
  19299. /**
  19300. * Computes the mesh World matrix and returns it.
  19301. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19302. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19303. * If the parameter `force`is set to `true`, the actual computation is done.
  19304. * Returns the mesh World Matrix.
  19305. */
  19306. TransformNode.prototype.computeWorldMatrix = function (force) {
  19307. if (this._isWorldMatrixFrozen) {
  19308. return this._worldMatrix;
  19309. }
  19310. if (!force && this.isSynchronized(true)) {
  19311. this._currentRenderId = this.getScene().getRenderId();
  19312. return this._worldMatrix;
  19313. }
  19314. this._cache.position.copyFrom(this.position);
  19315. this._cache.scaling.copyFrom(this.scaling);
  19316. this._cache.pivotMatrixUpdated = false;
  19317. this._cache.billboardMode = this.billboardMode;
  19318. this._currentRenderId = this.getScene().getRenderId();
  19319. this._childRenderId = this.getScene().getRenderId();
  19320. this._isDirty = false;
  19321. // Scaling
  19322. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19323. // Rotation
  19324. //rotate, if quaternion is set and rotation was used
  19325. if (this.rotationQuaternion) {
  19326. var len = this.rotation.length();
  19327. if (len) {
  19328. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19329. this.rotation.copyFromFloats(0, 0, 0);
  19330. }
  19331. }
  19332. if (this.rotationQuaternion) {
  19333. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19334. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19335. }
  19336. else {
  19337. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19338. this._cache.rotation.copyFrom(this.rotation);
  19339. }
  19340. // Translation
  19341. var camera = this.getScene().activeCamera;
  19342. if (this.infiniteDistance && !this.parent && camera) {
  19343. var cameraWorldMatrix = camera.getWorldMatrix();
  19344. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19345. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19346. }
  19347. else {
  19348. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19349. }
  19350. // Composing transformations
  19351. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19352. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19353. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19354. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19355. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19356. // Need to decompose each rotation here
  19357. var currentPosition = BABYLON.Tmp.Vector3[3];
  19358. if (this.parent && this.parent.getWorldMatrix) {
  19359. if (this._transformToBoneReferal) {
  19360. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19361. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19362. }
  19363. else {
  19364. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19365. }
  19366. }
  19367. else {
  19368. currentPosition.copyFrom(this.position);
  19369. }
  19370. currentPosition.subtractInPlace(camera.globalPosition);
  19371. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19372. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19373. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19374. }
  19375. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19376. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19377. }
  19378. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19379. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19380. }
  19381. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19382. }
  19383. else {
  19384. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19385. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19386. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19387. }
  19388. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19389. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19390. }
  19391. // Local world
  19392. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19393. // Parent
  19394. if (this.parent && this.parent.getWorldMatrix) {
  19395. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19396. if (this._transformToBoneReferal) {
  19397. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19398. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19399. }
  19400. else {
  19401. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19402. }
  19403. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19404. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19405. this._worldMatrix.copyFrom(this._localWorld);
  19406. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19407. }
  19408. else {
  19409. if (this._transformToBoneReferal) {
  19410. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19411. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19412. }
  19413. else {
  19414. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19415. }
  19416. }
  19417. this._markSyncedWithParent();
  19418. }
  19419. else {
  19420. this._worldMatrix.copyFrom(this._localWorld);
  19421. }
  19422. // Post multiply inverse of pivotMatrix
  19423. if (this._postMultiplyPivotMatrix) {
  19424. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19425. }
  19426. // Normal matrix
  19427. if (!this.ignoreNonUniformScaling) {
  19428. if (this.scaling.isNonUniform) {
  19429. this._updateNonUniformScalingState(true);
  19430. }
  19431. else if (this.parent && this.parent._nonUniformScaling) {
  19432. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19433. }
  19434. else {
  19435. this._updateNonUniformScalingState(false);
  19436. }
  19437. }
  19438. else {
  19439. this._updateNonUniformScalingState(false);
  19440. }
  19441. this._afterComputeWorldMatrix();
  19442. // Absolute position
  19443. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19444. // Callbacks
  19445. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19446. if (!this._poseMatrix) {
  19447. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19448. }
  19449. // Cache the determinant
  19450. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19451. return this._worldMatrix;
  19452. };
  19453. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19454. };
  19455. /**
  19456. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19457. * @param func: callback function to add
  19458. *
  19459. * Returns the TransformNode.
  19460. */
  19461. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19462. this.onAfterWorldMatrixUpdateObservable.add(func);
  19463. return this;
  19464. };
  19465. /**
  19466. * Removes a registered callback function.
  19467. * Returns the TransformNode.
  19468. */
  19469. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19470. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19471. return this;
  19472. };
  19473. /**
  19474. * Clone the current transform node
  19475. * Returns the new transform node
  19476. * @param name Name of the new clone
  19477. * @param newParent New parent for the clone
  19478. * @param doNotCloneChildren Do not clone children hierarchy
  19479. */
  19480. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19481. var _this = this;
  19482. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19483. result.name = name;
  19484. result.id = name;
  19485. if (newParent) {
  19486. result.parent = newParent;
  19487. }
  19488. if (!doNotCloneChildren) {
  19489. // Children
  19490. var directDescendants = this.getDescendants(true);
  19491. for (var index = 0; index < directDescendants.length; index++) {
  19492. var child = directDescendants[index];
  19493. if (child.clone) {
  19494. child.clone(name + "." + child.name, result);
  19495. }
  19496. }
  19497. }
  19498. return result;
  19499. };
  19500. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19501. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19502. serializationObject.type = this.getClassName();
  19503. // Parent
  19504. if (this.parent) {
  19505. serializationObject.parentId = this.parent.id;
  19506. }
  19507. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19508. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19509. }
  19510. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19511. serializationObject.isEnabled = this.isEnabled();
  19512. // Parent
  19513. if (this.parent) {
  19514. serializationObject.parentId = this.parent.id;
  19515. }
  19516. return serializationObject;
  19517. };
  19518. // Statics
  19519. /**
  19520. * Returns a new TransformNode object parsed from the source provided.
  19521. * The parameter `parsedMesh` is the source.
  19522. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19523. */
  19524. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19525. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19526. if (BABYLON.Tags) {
  19527. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19528. }
  19529. if (parsedTransformNode.localMatrix) {
  19530. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19531. }
  19532. else if (parsedTransformNode.pivotMatrix) {
  19533. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19534. }
  19535. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19536. // Parent
  19537. if (parsedTransformNode.parentId) {
  19538. transformNode._waitingParentId = parsedTransformNode.parentId;
  19539. }
  19540. return transformNode;
  19541. };
  19542. /**
  19543. * Releases resources associated with this transform node.
  19544. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19545. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19546. */
  19547. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19548. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19549. // Animations
  19550. this.getScene().stopAnimation(this);
  19551. // Remove from scene
  19552. this.getScene().removeTransformNode(this);
  19553. this.onAfterWorldMatrixUpdateObservable.clear();
  19554. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19555. };
  19556. // Statics
  19557. TransformNode.BILLBOARDMODE_NONE = 0;
  19558. TransformNode.BILLBOARDMODE_X = 1;
  19559. TransformNode.BILLBOARDMODE_Y = 2;
  19560. TransformNode.BILLBOARDMODE_Z = 4;
  19561. TransformNode.BILLBOARDMODE_ALL = 7;
  19562. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19563. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19564. __decorate([
  19565. BABYLON.serializeAsVector3()
  19566. ], TransformNode.prototype, "_rotation", void 0);
  19567. __decorate([
  19568. BABYLON.serializeAsQuaternion()
  19569. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19570. __decorate([
  19571. BABYLON.serializeAsVector3()
  19572. ], TransformNode.prototype, "_scaling", void 0);
  19573. __decorate([
  19574. BABYLON.serialize()
  19575. ], TransformNode.prototype, "billboardMode", void 0);
  19576. __decorate([
  19577. BABYLON.serialize()
  19578. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19579. __decorate([
  19580. BABYLON.serialize()
  19581. ], TransformNode.prototype, "infiniteDistance", void 0);
  19582. __decorate([
  19583. BABYLON.serialize()
  19584. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19585. __decorate([
  19586. BABYLON.serializeAsVector3()
  19587. ], TransformNode.prototype, "position", void 0);
  19588. return TransformNode;
  19589. }(BABYLON.Node));
  19590. BABYLON.TransformNode = TransformNode;
  19591. })(BABYLON || (BABYLON = {}));
  19592. //# sourceMappingURL=babylon.transformNode.js.map
  19593. var BABYLON;
  19594. (function (BABYLON) {
  19595. /**
  19596. * Class used to store all common mesh properties
  19597. */
  19598. var AbstractMesh = /** @class */ (function (_super) {
  19599. __extends(AbstractMesh, _super);
  19600. // Constructor
  19601. /**
  19602. * Creates a new AbstractMesh
  19603. * @param name defines the name of the mesh
  19604. * @param scene defines the hosting scene
  19605. */
  19606. function AbstractMesh(name, scene) {
  19607. if (scene === void 0) { scene = null; }
  19608. var _this = _super.call(this, name, scene, false) || this;
  19609. _this._facetNb = 0; // facet number
  19610. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19611. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19612. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19613. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19614. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19615. _this._subDiv = {
  19616. max: 1,
  19617. X: 1,
  19618. Y: 1,
  19619. Z: 1
  19620. };
  19621. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19622. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19623. // Events
  19624. /**
  19625. * An event triggered when this mesh collides with another one
  19626. */
  19627. _this.onCollideObservable = new BABYLON.Observable();
  19628. /**
  19629. * An event triggered when the collision's position changes
  19630. */
  19631. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19632. /**
  19633. * An event triggered when material is changed
  19634. */
  19635. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19636. // Properties
  19637. /**
  19638. * Gets or sets the orientation for POV movement & rotation
  19639. */
  19640. _this.definedFacingForward = true;
  19641. /**
  19642. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19643. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19644. * * 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.
  19645. * @see http://doc.babylonjs.com/features/occlusionquery
  19646. */
  19647. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19648. /**
  19649. * 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:
  19650. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19651. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19652. * * 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.
  19653. * @see http://doc.babylonjs.com/features/occlusionquery
  19654. */
  19655. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19656. /**
  19657. * 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.
  19658. * The default value is -1 which means don't break the query and wait till the result
  19659. * @see http://doc.babylonjs.com/features/occlusionquery
  19660. */
  19661. _this.occlusionRetryCount = -1;
  19662. _this._occlusionInternalRetryCounter = 0;
  19663. _this._isOccluded = false;
  19664. _this._isOcclusionQueryInProgress = false;
  19665. _this._visibility = 1.0;
  19666. /** Gets or sets the alpha index used to sort transparent meshes
  19667. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19668. */
  19669. _this.alphaIndex = Number.MAX_VALUE;
  19670. /**
  19671. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19672. */
  19673. _this.isVisible = true;
  19674. /**
  19675. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19676. */
  19677. _this.isPickable = true;
  19678. /**
  19679. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19680. */
  19681. _this.showBoundingBox = false;
  19682. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19683. _this.showSubMeshesBoundingBox = false;
  19684. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19685. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19686. */
  19687. _this.isBlocker = false;
  19688. /**
  19689. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19690. */
  19691. _this.enablePointerMoveEvents = false;
  19692. /**
  19693. * Specifies the rendering group id for this mesh (0 by default)
  19694. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19695. */
  19696. _this.renderingGroupId = 0;
  19697. _this._receiveShadows = false;
  19698. /**
  19699. * Gets or sets a boolean indicating if the outline must be rendered as well
  19700. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19701. */
  19702. _this.renderOutline = false;
  19703. /** Defines color to use when rendering outline */
  19704. _this.outlineColor = BABYLON.Color3.Red();
  19705. /** Define width to use when rendering outline */
  19706. _this.outlineWidth = 0.02;
  19707. /**
  19708. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19709. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19710. */
  19711. _this.renderOverlay = false;
  19712. /** Defines color to use when rendering overlay */
  19713. _this.overlayColor = BABYLON.Color3.Red();
  19714. /** Defines alpha to use when rendering overlay */
  19715. _this.overlayAlpha = 0.5;
  19716. _this._hasVertexAlpha = false;
  19717. _this._useVertexColors = true;
  19718. _this._computeBonesUsingShaders = true;
  19719. _this._numBoneInfluencers = 4;
  19720. _this._applyFog = true;
  19721. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19722. _this.useOctreeForRenderingSelection = true;
  19723. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19724. _this.useOctreeForPicking = true;
  19725. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19726. _this.useOctreeForCollisions = true;
  19727. _this._layerMask = 0x0FFFFFFF;
  19728. /**
  19729. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19730. */
  19731. _this.alwaysSelectAsActiveMesh = false;
  19732. /**
  19733. * Gets or sets the current action manager
  19734. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19735. */
  19736. _this.actionManager = null;
  19737. /**
  19738. * Gets or sets impostor used for physic simulation
  19739. * @see http://doc.babylonjs.com/features/physics_engine
  19740. */
  19741. _this.physicsImpostor = null;
  19742. // Collisions
  19743. _this._checkCollisions = false;
  19744. _this._collisionMask = -1;
  19745. _this._collisionGroup = -1;
  19746. /**
  19747. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19748. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19749. */
  19750. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19751. /**
  19752. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19753. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19754. */
  19755. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19756. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19757. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19758. // Edges
  19759. /**
  19760. * Defines edge width used when edgesRenderer is enabled
  19761. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19762. */
  19763. _this.edgesWidth = 1;
  19764. /**
  19765. * Defines edge color used when edgesRenderer is enabled
  19766. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19767. */
  19768. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19769. // Cache
  19770. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19771. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19772. /** @hidden */
  19773. _this._renderId = 0;
  19774. /** @hidden */
  19775. _this._intersectionsInProgress = new Array();
  19776. /** @hidden */
  19777. _this._unIndexed = false;
  19778. /** @hidden */
  19779. _this._lightSources = new Array();
  19780. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19781. if (collidedMesh === void 0) { collidedMesh = null; }
  19782. //TODO move this to the collision coordinator!
  19783. if (_this.getScene().workerCollisions)
  19784. newPosition.multiplyInPlace(_this._collider._radius);
  19785. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19786. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19787. _this.position.addInPlace(_this._diffPositionForCollisions);
  19788. }
  19789. if (collidedMesh) {
  19790. _this.onCollideObservable.notifyObservers(collidedMesh);
  19791. }
  19792. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19793. };
  19794. _this.getScene().addMesh(_this);
  19795. _this._resyncLightSources();
  19796. return _this;
  19797. }
  19798. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19799. /**
  19800. * No billboard
  19801. */
  19802. get: function () {
  19803. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19809. /** Billboard on X axis */
  19810. get: function () {
  19811. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19817. /** Billboard on Y axis */
  19818. get: function () {
  19819. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19825. /** Billboard on Z axis */
  19826. get: function () {
  19827. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19833. /** Billboard on all axes */
  19834. get: function () {
  19835. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19836. },
  19837. enumerable: true,
  19838. configurable: true
  19839. });
  19840. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19841. /**
  19842. * Gets the number of facets in the mesh
  19843. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19844. */
  19845. get: function () {
  19846. return this._facetNb;
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19852. /**
  19853. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19854. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19855. */
  19856. get: function () {
  19857. return this._partitioningSubdivisions;
  19858. },
  19859. set: function (nb) {
  19860. this._partitioningSubdivisions = nb;
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19866. /**
  19867. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19868. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19869. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19870. */
  19871. get: function () {
  19872. return this._partitioningBBoxRatio;
  19873. },
  19874. set: function (ratio) {
  19875. this._partitioningBBoxRatio = ratio;
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19881. /**
  19882. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19883. * Works only for updatable meshes.
  19884. * Doesn't work with multi-materials
  19885. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19886. */
  19887. get: function () {
  19888. return this._facetDepthSort;
  19889. },
  19890. set: function (sort) {
  19891. this._facetDepthSort = sort;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19897. /**
  19898. * The location (Vector3) where the facet depth sort must be computed from.
  19899. * By default, the active camera position.
  19900. * Used only when facet depth sort is enabled
  19901. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19902. */
  19903. get: function () {
  19904. return this._facetDepthSortFrom;
  19905. },
  19906. set: function (location) {
  19907. this._facetDepthSortFrom = location;
  19908. },
  19909. enumerable: true,
  19910. configurable: true
  19911. });
  19912. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19913. /**
  19914. * gets a boolean indicating if facetData is enabled
  19915. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19916. */
  19917. get: function () {
  19918. return this._facetDataEnabled;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. /** @hidden */
  19924. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19925. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19926. return false;
  19927. }
  19928. this._markSubMeshesAsMiscDirty();
  19929. return true;
  19930. };
  19931. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19932. /** Set a function to call when this mesh collides with another one */
  19933. set: function (callback) {
  19934. if (this._onCollideObserver) {
  19935. this.onCollideObservable.remove(this._onCollideObserver);
  19936. }
  19937. this._onCollideObserver = this.onCollideObservable.add(callback);
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19943. /** Set a function to call when the collision's position changes */
  19944. set: function (callback) {
  19945. if (this._onCollisionPositionChangeObserver) {
  19946. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19947. }
  19948. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19949. },
  19950. enumerable: true,
  19951. configurable: true
  19952. });
  19953. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19954. /**
  19955. * 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
  19956. * @see http://doc.babylonjs.com/features/occlusionquery
  19957. */
  19958. get: function () {
  19959. return this._isOccluded;
  19960. },
  19961. set: function (value) {
  19962. this._isOccluded = value;
  19963. },
  19964. enumerable: true,
  19965. configurable: true
  19966. });
  19967. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19968. /**
  19969. * Flag to check the progress status of the query
  19970. * @see http://doc.babylonjs.com/features/occlusionquery
  19971. */
  19972. get: function () {
  19973. return this._isOcclusionQueryInProgress;
  19974. },
  19975. enumerable: true,
  19976. configurable: true
  19977. });
  19978. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19979. /**
  19980. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19981. */
  19982. get: function () {
  19983. return this._visibility;
  19984. },
  19985. /**
  19986. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19987. */
  19988. set: function (value) {
  19989. if (this._visibility === value) {
  19990. return;
  19991. }
  19992. this._visibility = value;
  19993. this._markSubMeshesAsMiscDirty();
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. Object.defineProperty(AbstractMesh.prototype, "material", {
  19999. /** Gets or sets current material */
  20000. get: function () {
  20001. return this._material;
  20002. },
  20003. set: function (value) {
  20004. if (this._material === value) {
  20005. return;
  20006. }
  20007. this._material = value;
  20008. if (this.onMaterialChangedObservable.hasObservers) {
  20009. this.onMaterialChangedObservable.notifyObservers(this);
  20010. }
  20011. if (!this.subMeshes) {
  20012. return;
  20013. }
  20014. this._unBindEffect();
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20020. /**
  20021. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20022. * @see http://doc.babylonjs.com/babylon101/shadows
  20023. */
  20024. get: function () {
  20025. return this._receiveShadows;
  20026. },
  20027. set: function (value) {
  20028. if (this._receiveShadows === value) {
  20029. return;
  20030. }
  20031. this._receiveShadows = value;
  20032. this._markSubMeshesAsLightDirty();
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20038. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20039. get: function () {
  20040. return this._hasVertexAlpha;
  20041. },
  20042. set: function (value) {
  20043. if (this._hasVertexAlpha === value) {
  20044. return;
  20045. }
  20046. this._hasVertexAlpha = value;
  20047. this._markSubMeshesAsAttributesDirty();
  20048. this._markSubMeshesAsMiscDirty();
  20049. },
  20050. enumerable: true,
  20051. configurable: true
  20052. });
  20053. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20054. /** 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) */
  20055. get: function () {
  20056. return this._useVertexColors;
  20057. },
  20058. set: function (value) {
  20059. if (this._useVertexColors === value) {
  20060. return;
  20061. }
  20062. this._useVertexColors = value;
  20063. this._markSubMeshesAsAttributesDirty();
  20064. },
  20065. enumerable: true,
  20066. configurable: true
  20067. });
  20068. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20069. /**
  20070. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20071. */
  20072. get: function () {
  20073. return this._computeBonesUsingShaders;
  20074. },
  20075. set: function (value) {
  20076. if (this._computeBonesUsingShaders === value) {
  20077. return;
  20078. }
  20079. this._computeBonesUsingShaders = value;
  20080. this._markSubMeshesAsAttributesDirty();
  20081. },
  20082. enumerable: true,
  20083. configurable: true
  20084. });
  20085. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20086. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20087. get: function () {
  20088. return this._numBoneInfluencers;
  20089. },
  20090. set: function (value) {
  20091. if (this._numBoneInfluencers === value) {
  20092. return;
  20093. }
  20094. this._numBoneInfluencers = value;
  20095. this._markSubMeshesAsAttributesDirty();
  20096. },
  20097. enumerable: true,
  20098. configurable: true
  20099. });
  20100. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20101. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20102. get: function () {
  20103. return this._applyFog;
  20104. },
  20105. set: function (value) {
  20106. if (this._applyFog === value) {
  20107. return;
  20108. }
  20109. this._applyFog = value;
  20110. this._markSubMeshesAsMiscDirty();
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20116. /**
  20117. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20118. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20119. */
  20120. get: function () {
  20121. return this._layerMask;
  20122. },
  20123. set: function (value) {
  20124. if (value === this._layerMask) {
  20125. return;
  20126. }
  20127. this._layerMask = value;
  20128. this._resyncLightSources();
  20129. },
  20130. enumerable: true,
  20131. configurable: true
  20132. });
  20133. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20134. /**
  20135. * Gets or sets a collision mask used to mask collisions (default is -1).
  20136. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20137. */
  20138. get: function () {
  20139. return this._collisionMask;
  20140. },
  20141. set: function (mask) {
  20142. this._collisionMask = !isNaN(mask) ? mask : -1;
  20143. },
  20144. enumerable: true,
  20145. configurable: true
  20146. });
  20147. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20148. /**
  20149. * Gets or sets the current collision group mask (-1 by default).
  20150. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20151. */
  20152. get: function () {
  20153. return this._collisionGroup;
  20154. },
  20155. set: function (mask) {
  20156. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20157. },
  20158. enumerable: true,
  20159. configurable: true
  20160. });
  20161. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20162. /** @hidden */
  20163. get: function () {
  20164. return null;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20170. get: function () {
  20171. return this._skeleton;
  20172. },
  20173. /**
  20174. * Gets or sets a skeleton to apply skining transformations
  20175. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20176. */
  20177. set: function (value) {
  20178. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20179. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20180. }
  20181. if (value && value.needInitialSkinMatrix) {
  20182. value._registerMeshWithPoseMatrix(this);
  20183. }
  20184. this._skeleton = value;
  20185. if (!this._skeleton) {
  20186. this._bonesTransformMatrices = null;
  20187. }
  20188. this._markSubMeshesAsAttributesDirty();
  20189. },
  20190. enumerable: true,
  20191. configurable: true
  20192. });
  20193. /**
  20194. * Returns the string "AbstractMesh"
  20195. * @returns "AbstractMesh"
  20196. */
  20197. AbstractMesh.prototype.getClassName = function () {
  20198. return "AbstractMesh";
  20199. };
  20200. /**
  20201. * Gets a string representation of the current mesh
  20202. * @param fullDetails defines a boolean indicating if full details must be included
  20203. * @returns a string representation of the current mesh
  20204. */
  20205. AbstractMesh.prototype.toString = function (fullDetails) {
  20206. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20207. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20208. if (this._skeleton) {
  20209. ret += ", skeleton: " + this._skeleton.name;
  20210. }
  20211. if (fullDetails) {
  20212. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20213. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20214. }
  20215. return ret;
  20216. };
  20217. /** @hidden */
  20218. AbstractMesh.prototype._rebuild = function () {
  20219. if (this._occlusionQuery) {
  20220. this._occlusionQuery = null;
  20221. }
  20222. if (this._edgesRenderer) {
  20223. this._edgesRenderer._rebuild();
  20224. }
  20225. if (!this.subMeshes) {
  20226. return;
  20227. }
  20228. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20229. var subMesh = _a[_i];
  20230. subMesh._rebuild();
  20231. }
  20232. };
  20233. /** @hidden */
  20234. AbstractMesh.prototype._resyncLightSources = function () {
  20235. this._lightSources.length = 0;
  20236. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20237. var light = _a[_i];
  20238. if (!light.isEnabled()) {
  20239. continue;
  20240. }
  20241. if (light.canAffectMesh(this)) {
  20242. this._lightSources.push(light);
  20243. }
  20244. }
  20245. this._markSubMeshesAsLightDirty();
  20246. };
  20247. /** @hidden */
  20248. AbstractMesh.prototype._resyncLighSource = function (light) {
  20249. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20250. var index = this._lightSources.indexOf(light);
  20251. if (index === -1) {
  20252. if (!isIn) {
  20253. return;
  20254. }
  20255. this._lightSources.push(light);
  20256. }
  20257. else {
  20258. if (isIn) {
  20259. return;
  20260. }
  20261. this._lightSources.splice(index, 1);
  20262. }
  20263. this._markSubMeshesAsLightDirty();
  20264. };
  20265. /** @hidden */
  20266. AbstractMesh.prototype._unBindEffect = function () {
  20267. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20268. var subMesh = _a[_i];
  20269. subMesh.setEffect(null);
  20270. }
  20271. };
  20272. /** @hidden */
  20273. AbstractMesh.prototype._removeLightSource = function (light) {
  20274. var index = this._lightSources.indexOf(light);
  20275. if (index === -1) {
  20276. return;
  20277. }
  20278. this._lightSources.splice(index, 1);
  20279. this._markSubMeshesAsLightDirty();
  20280. };
  20281. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20282. if (!this.subMeshes) {
  20283. return;
  20284. }
  20285. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20286. var subMesh = _a[_i];
  20287. if (subMesh._materialDefines) {
  20288. func(subMesh._materialDefines);
  20289. }
  20290. }
  20291. };
  20292. /** @hidden */
  20293. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20294. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20295. };
  20296. /** @hidden */
  20297. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20298. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20299. };
  20300. /** @hidden */
  20301. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20302. if (!this.subMeshes) {
  20303. return;
  20304. }
  20305. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20306. var subMesh = _a[_i];
  20307. var material = subMesh.getMaterial();
  20308. if (material) {
  20309. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20310. }
  20311. }
  20312. };
  20313. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20314. /**
  20315. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20316. */
  20317. get: function () {
  20318. return this._scaling;
  20319. },
  20320. set: function (newScaling) {
  20321. this._scaling = newScaling;
  20322. if (this.physicsImpostor) {
  20323. this.physicsImpostor.forceUpdate();
  20324. }
  20325. },
  20326. enumerable: true,
  20327. configurable: true
  20328. });
  20329. // Methods
  20330. /**
  20331. * Disables the mesh edge rendering mode
  20332. * @returns the currentAbstractMesh
  20333. */
  20334. AbstractMesh.prototype.disableEdgesRendering = function () {
  20335. if (this._edgesRenderer) {
  20336. this._edgesRenderer.dispose();
  20337. this._edgesRenderer = null;
  20338. }
  20339. return this;
  20340. };
  20341. /**
  20342. * Enables the edge rendering mode on the mesh.
  20343. * This mode makes the mesh edges visible
  20344. * @param epsilon defines the maximal distance between two angles to detect a face
  20345. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20346. * @returns the currentAbstractMesh
  20347. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20348. */
  20349. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20350. if (epsilon === void 0) { epsilon = 0.95; }
  20351. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20352. this.disableEdgesRendering();
  20353. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20354. return this;
  20355. };
  20356. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20357. /**
  20358. * Gets the edgesRenderer associated with the mesh
  20359. */
  20360. get: function () {
  20361. return this._edgesRenderer;
  20362. },
  20363. enumerable: true,
  20364. configurable: true
  20365. });
  20366. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20367. /**
  20368. * Returns true if the mesh is blocked. Implemented by child classes
  20369. */
  20370. get: function () {
  20371. return false;
  20372. },
  20373. enumerable: true,
  20374. configurable: true
  20375. });
  20376. /**
  20377. * Returns the mesh itself by default. Implemented by child classes
  20378. * @param camera defines the camera to use to pick the right LOD level
  20379. * @returns the currentAbstractMesh
  20380. */
  20381. AbstractMesh.prototype.getLOD = function (camera) {
  20382. return this;
  20383. };
  20384. /**
  20385. * Returns 0 by default. Implemented by child classes
  20386. * @returns an integer
  20387. */
  20388. AbstractMesh.prototype.getTotalVertices = function () {
  20389. return 0;
  20390. };
  20391. /**
  20392. * Returns null by default. Implemented by child classes
  20393. * @returns null
  20394. */
  20395. AbstractMesh.prototype.getIndices = function () {
  20396. return null;
  20397. };
  20398. /**
  20399. * Returns the array of the requested vertex data kind. Implemented by child classes
  20400. * @param kind defines the vertex data kind to use
  20401. * @returns null
  20402. */
  20403. AbstractMesh.prototype.getVerticesData = function (kind) {
  20404. return null;
  20405. };
  20406. /**
  20407. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20408. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20409. * Note that a new underlying VertexBuffer object is created each call.
  20410. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20411. * @param kind defines vertex data kind:
  20412. * * BABYLON.VertexBuffer.PositionKind
  20413. * * BABYLON.VertexBuffer.UVKind
  20414. * * BABYLON.VertexBuffer.UV2Kind
  20415. * * BABYLON.VertexBuffer.UV3Kind
  20416. * * BABYLON.VertexBuffer.UV4Kind
  20417. * * BABYLON.VertexBuffer.UV5Kind
  20418. * * BABYLON.VertexBuffer.UV6Kind
  20419. * * BABYLON.VertexBuffer.ColorKind
  20420. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20421. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20422. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20423. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20424. * @param data defines the data source
  20425. * @param updatable defines if the data must be flagged as updatable (or static)
  20426. * @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
  20427. * @returns the current mesh
  20428. */
  20429. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20430. return this;
  20431. };
  20432. /**
  20433. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20434. * If the mesh has no geometry, it is simply returned as it is.
  20435. * @param kind defines vertex data kind:
  20436. * * BABYLON.VertexBuffer.PositionKind
  20437. * * BABYLON.VertexBuffer.UVKind
  20438. * * BABYLON.VertexBuffer.UV2Kind
  20439. * * BABYLON.VertexBuffer.UV3Kind
  20440. * * BABYLON.VertexBuffer.UV4Kind
  20441. * * BABYLON.VertexBuffer.UV5Kind
  20442. * * BABYLON.VertexBuffer.UV6Kind
  20443. * * BABYLON.VertexBuffer.ColorKind
  20444. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20445. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20446. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20447. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20448. * @param data defines the data source
  20449. * @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
  20450. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20451. * @returns the current mesh
  20452. */
  20453. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20454. return this;
  20455. };
  20456. /**
  20457. * Sets the mesh indices,
  20458. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20459. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20460. * @param totalVertices Defines the total number of vertices
  20461. * @returns the current mesh
  20462. */
  20463. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20464. return this;
  20465. };
  20466. /**
  20467. * Gets a boolean indicating if specific vertex data is present
  20468. * @param kind defines the vertex data kind to use
  20469. * @returns true is data kind is present
  20470. */
  20471. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20472. return false;
  20473. };
  20474. /**
  20475. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20476. * @returns a BoundingInfo
  20477. */
  20478. AbstractMesh.prototype.getBoundingInfo = function () {
  20479. if (this._masterMesh) {
  20480. return this._masterMesh.getBoundingInfo();
  20481. }
  20482. if (!this._boundingInfo) {
  20483. // this._boundingInfo is being created here
  20484. this._updateBoundingInfo();
  20485. }
  20486. // cannot be null.
  20487. return this._boundingInfo;
  20488. };
  20489. /**
  20490. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20491. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20492. * @returns the current mesh
  20493. */
  20494. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20495. if (includeDescendants === void 0) { includeDescendants = true; }
  20496. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20497. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20498. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20499. if (maxDimension === 0) {
  20500. return this;
  20501. }
  20502. var scale = 1 / maxDimension;
  20503. this.scaling.scaleInPlace(scale);
  20504. return this;
  20505. };
  20506. /**
  20507. * Overwrite the current bounding info
  20508. * @param boundingInfo defines the new bounding info
  20509. * @returns the current mesh
  20510. */
  20511. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20512. this._boundingInfo = boundingInfo;
  20513. return this;
  20514. };
  20515. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20516. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20517. get: function () {
  20518. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20519. },
  20520. enumerable: true,
  20521. configurable: true
  20522. });
  20523. /** @hidden */
  20524. AbstractMesh.prototype._preActivate = function () {
  20525. };
  20526. /** @hidden */
  20527. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20528. };
  20529. /** @hidden */
  20530. AbstractMesh.prototype._activate = function (renderId) {
  20531. this._renderId = renderId;
  20532. };
  20533. /**
  20534. * Gets the current world matrix
  20535. * @returns a Matrix
  20536. */
  20537. AbstractMesh.prototype.getWorldMatrix = function () {
  20538. if (this._masterMesh) {
  20539. return this._masterMesh.getWorldMatrix();
  20540. }
  20541. return _super.prototype.getWorldMatrix.call(this);
  20542. };
  20543. /** @hidden */
  20544. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20545. if (this._masterMesh) {
  20546. return this._masterMesh._getWorldMatrixDeterminant();
  20547. }
  20548. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20549. };
  20550. // ================================== Point of View Movement =================================
  20551. /**
  20552. * Perform relative position change from the point of view of behind the front of the mesh.
  20553. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20554. * Supports definition of mesh facing forward or backward
  20555. * @param amountRight defines the distance on the right axis
  20556. * @param amountUp defines the distance on the up axis
  20557. * @param amountForward defines the distance on the forward axis
  20558. * @returns the current mesh
  20559. */
  20560. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20561. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20562. return this;
  20563. };
  20564. /**
  20565. * Calculate relative position change from the point of view of behind the front of the mesh.
  20566. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20567. * Supports definition of mesh facing forward or backward
  20568. * @param amountRight defines the distance on the right axis
  20569. * @param amountUp defines the distance on the up axis
  20570. * @param amountForward defines the distance on the forward axis
  20571. * @returns the new displacement vector
  20572. */
  20573. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20574. var rotMatrix = new BABYLON.Matrix();
  20575. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20576. rotQuaternion.toRotationMatrix(rotMatrix);
  20577. var translationDelta = BABYLON.Vector3.Zero();
  20578. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20579. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20580. return translationDelta;
  20581. };
  20582. // ================================== Point of View Rotation =================================
  20583. /**
  20584. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20585. * Supports definition of mesh facing forward or backward
  20586. * @param flipBack defines the flip
  20587. * @param twirlClockwise defines the twirl
  20588. * @param tiltRight defines the tilt
  20589. * @returns the current mesh
  20590. */
  20591. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20592. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20593. return this;
  20594. };
  20595. /**
  20596. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20597. * Supports definition of mesh facing forward or backward.
  20598. * @param flipBack defines the flip
  20599. * @param twirlClockwise defines the twirl
  20600. * @param tiltRight defines the tilt
  20601. * @returns the new rotation vector
  20602. */
  20603. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20604. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20605. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20606. };
  20607. /**
  20608. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20609. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20610. * @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
  20611. * @returns the new bounding vectors
  20612. */
  20613. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20614. if (includeDescendants === void 0) { includeDescendants = true; }
  20615. if (predicate === void 0) { predicate = null; }
  20616. // Ensures that all world matrix will be recomputed.
  20617. this.getScene().incrementRenderId();
  20618. this.computeWorldMatrix(true);
  20619. var min;
  20620. var max;
  20621. var boundingInfo = this.getBoundingInfo();
  20622. if (!this.subMeshes) {
  20623. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20624. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20625. }
  20626. else {
  20627. min = boundingInfo.boundingBox.minimumWorld;
  20628. max = boundingInfo.boundingBox.maximumWorld;
  20629. }
  20630. if (includeDescendants) {
  20631. var descendants = this.getDescendants(false);
  20632. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20633. var descendant = descendants_1[_i];
  20634. var childMesh = descendant;
  20635. childMesh.computeWorldMatrix(true);
  20636. // Filters meshes based on custom predicate function.
  20637. if (predicate && !predicate(childMesh)) {
  20638. continue;
  20639. }
  20640. //make sure we have the needed params to get mix and max
  20641. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20642. continue;
  20643. }
  20644. var childBoundingInfo = childMesh.getBoundingInfo();
  20645. var boundingBox = childBoundingInfo.boundingBox;
  20646. var minBox = boundingBox.minimumWorld;
  20647. var maxBox = boundingBox.maximumWorld;
  20648. BABYLON.Tools.CheckExtends(minBox, min, max);
  20649. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20650. }
  20651. }
  20652. return {
  20653. min: min,
  20654. max: max
  20655. };
  20656. };
  20657. /** @hidden */
  20658. AbstractMesh.prototype._updateBoundingInfo = function () {
  20659. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20660. this._boundingInfo.update(this.worldMatrixFromCache);
  20661. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20662. return this;
  20663. };
  20664. /** @hidden */
  20665. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20666. if (!this.subMeshes) {
  20667. return this;
  20668. }
  20669. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20670. var subMesh = this.subMeshes[subIndex];
  20671. if (!subMesh.IsGlobal) {
  20672. subMesh.updateBoundingInfo(matrix);
  20673. }
  20674. }
  20675. return this;
  20676. };
  20677. /** @hidden */
  20678. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20679. // Bounding info
  20680. this._updateBoundingInfo();
  20681. };
  20682. /**
  20683. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20684. * A mesh is in the frustum if its bounding box intersects the frustum
  20685. * @param frustumPlanes defines the frustum to test
  20686. * @returns true if the mesh is in the frustum planes
  20687. */
  20688. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20689. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20690. };
  20691. /**
  20692. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20693. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20694. * @param frustumPlanes defines the frustum to test
  20695. * @returns true if the mesh is completely in the frustum planes
  20696. */
  20697. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20698. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20699. };
  20700. /**
  20701. * True if the mesh intersects another mesh or a SolidParticle object
  20702. * @param mesh defines a target mesh or SolidParticle to test
  20703. * @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)
  20704. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20705. * @returns true if there is an intersection
  20706. */
  20707. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20708. if (precise === void 0) { precise = false; }
  20709. if (!this._boundingInfo || !mesh._boundingInfo) {
  20710. return false;
  20711. }
  20712. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20713. return true;
  20714. }
  20715. if (includeDescendants) {
  20716. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20717. var child = _a[_i];
  20718. if (child.intersectsMesh(mesh, precise, true)) {
  20719. return true;
  20720. }
  20721. }
  20722. }
  20723. return false;
  20724. };
  20725. /**
  20726. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20727. * @param point defines the point to test
  20728. * @returns true if there is an intersection
  20729. */
  20730. AbstractMesh.prototype.intersectsPoint = function (point) {
  20731. if (!this._boundingInfo) {
  20732. return false;
  20733. }
  20734. return this._boundingInfo.intersectsPoint(point);
  20735. };
  20736. /**
  20737. * Gets the current physics impostor
  20738. * @see http://doc.babylonjs.com/features/physics_engine
  20739. * @returns a physics impostor or null
  20740. */
  20741. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20742. return this.physicsImpostor;
  20743. };
  20744. /**
  20745. * Gets the position of the current mesh in camera space
  20746. * @param camera defines the camera to use
  20747. * @returns a position
  20748. */
  20749. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20750. if (camera === void 0) { camera = null; }
  20751. if (!camera) {
  20752. camera = this.getScene().activeCamera;
  20753. }
  20754. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20755. };
  20756. /**
  20757. * Returns the distance from the mesh to the active camera
  20758. * @param camera defines the camera to use
  20759. * @returns the distance
  20760. */
  20761. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20762. if (camera === void 0) { camera = null; }
  20763. if (!camera) {
  20764. camera = this.getScene().activeCamera;
  20765. }
  20766. return this.absolutePosition.subtract(camera.position).length();
  20767. };
  20768. /**
  20769. * Apply a physic impulse to the mesh
  20770. * @param force defines the force to apply
  20771. * @param contactPoint defines where to apply the force
  20772. * @returns the current mesh
  20773. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20774. */
  20775. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20776. if (!this.physicsImpostor) {
  20777. return this;
  20778. }
  20779. this.physicsImpostor.applyImpulse(force, contactPoint);
  20780. return this;
  20781. };
  20782. /**
  20783. * Creates a physic joint between two meshes
  20784. * @param otherMesh defines the other mesh to use
  20785. * @param pivot1 defines the pivot to use on this mesh
  20786. * @param pivot2 defines the pivot to use on the other mesh
  20787. * @param options defines additional options (can be plugin dependent)
  20788. * @returns the current mesh
  20789. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20790. */
  20791. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20792. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20793. return this;
  20794. }
  20795. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20796. mainPivot: pivot1,
  20797. connectedPivot: pivot2,
  20798. nativeParams: options
  20799. });
  20800. return this;
  20801. };
  20802. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20803. // Collisions
  20804. /**
  20805. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20806. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20807. */
  20808. get: function () {
  20809. return this._checkCollisions;
  20810. },
  20811. set: function (collisionEnabled) {
  20812. this._checkCollisions = collisionEnabled;
  20813. if (this.getScene().workerCollisions) {
  20814. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20815. }
  20816. },
  20817. enumerable: true,
  20818. configurable: true
  20819. });
  20820. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20821. /**
  20822. * Gets Collider object used to compute collisions (not physics)
  20823. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20824. */
  20825. get: function () {
  20826. return this._collider;
  20827. },
  20828. enumerable: true,
  20829. configurable: true
  20830. });
  20831. /**
  20832. * Move the mesh using collision engine
  20833. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20834. * @param displacement defines the requested displacement vector
  20835. * @returns the current mesh
  20836. */
  20837. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20838. var globalPosition = this.getAbsolutePosition();
  20839. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20840. if (!this._collider) {
  20841. this._collider = new BABYLON.Collider();
  20842. }
  20843. this._collider._radius = this.ellipsoid;
  20844. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20845. return this;
  20846. };
  20847. // Submeshes octree
  20848. /**
  20849. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20850. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20851. * @param maxCapacity defines the maximum size of each block (64 by default)
  20852. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20853. * @returns the new octree
  20854. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20855. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20856. */
  20857. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20858. if (maxCapacity === void 0) { maxCapacity = 64; }
  20859. if (maxDepth === void 0) { maxDepth = 2; }
  20860. if (!this._submeshesOctree) {
  20861. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20862. }
  20863. this.computeWorldMatrix(true);
  20864. var boundingInfo = this.getBoundingInfo();
  20865. // Update octree
  20866. var bbox = boundingInfo.boundingBox;
  20867. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20868. return this._submeshesOctree;
  20869. };
  20870. // Collisions
  20871. /** @hidden */
  20872. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20873. this._generatePointsArray();
  20874. if (!this._positions) {
  20875. return this;
  20876. }
  20877. // Transformation
  20878. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20879. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20880. subMesh._lastColliderWorldVertices = [];
  20881. subMesh._trianglePlanes = [];
  20882. var start = subMesh.verticesStart;
  20883. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20884. for (var i = start; i < end; i++) {
  20885. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20886. }
  20887. }
  20888. // Collide
  20889. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20890. if (collider.collisionFound) {
  20891. collider.collidedMesh = this;
  20892. }
  20893. return this;
  20894. };
  20895. /** @hidden */
  20896. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20897. var subMeshes;
  20898. var len;
  20899. // Octrees
  20900. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20901. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20902. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20903. len = intersections.length;
  20904. subMeshes = intersections.data;
  20905. }
  20906. else {
  20907. subMeshes = this.subMeshes;
  20908. len = subMeshes.length;
  20909. }
  20910. for (var index = 0; index < len; index++) {
  20911. var subMesh = subMeshes[index];
  20912. // Bounding test
  20913. if (len > 1 && !subMesh._checkCollision(collider))
  20914. continue;
  20915. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20916. }
  20917. return this;
  20918. };
  20919. /** @hidden */
  20920. AbstractMesh.prototype._checkCollision = function (collider) {
  20921. // Bounding box test
  20922. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20923. return this;
  20924. // Transformation matrix
  20925. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20926. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20927. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20928. return this;
  20929. };
  20930. // Picking
  20931. /** @hidden */
  20932. AbstractMesh.prototype._generatePointsArray = function () {
  20933. return false;
  20934. };
  20935. /**
  20936. * Checks if the passed Ray intersects with the mesh
  20937. * @param ray defines the ray to use
  20938. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20939. * @returns the picking info
  20940. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20941. */
  20942. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20943. var pickingInfo = new BABYLON.PickingInfo();
  20944. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20945. return pickingInfo;
  20946. }
  20947. if (!this._generatePointsArray()) {
  20948. return pickingInfo;
  20949. }
  20950. var intersectInfo = null;
  20951. // Octrees
  20952. var subMeshes;
  20953. var len;
  20954. if (this._submeshesOctree && this.useOctreeForPicking) {
  20955. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20956. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20957. len = intersections.length;
  20958. subMeshes = intersections.data;
  20959. }
  20960. else {
  20961. subMeshes = this.subMeshes;
  20962. len = subMeshes.length;
  20963. }
  20964. for (var index = 0; index < len; index++) {
  20965. var subMesh = subMeshes[index];
  20966. // Bounding test
  20967. if (len > 1 && !subMesh.canIntersects(ray))
  20968. continue;
  20969. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20970. if (currentIntersectInfo) {
  20971. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20972. intersectInfo = currentIntersectInfo;
  20973. intersectInfo.subMeshId = index;
  20974. if (fastCheck) {
  20975. break;
  20976. }
  20977. }
  20978. }
  20979. }
  20980. if (intersectInfo) {
  20981. // Get picked point
  20982. var world = this.getWorldMatrix();
  20983. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20984. var direction = ray.direction.clone();
  20985. direction = direction.scale(intersectInfo.distance);
  20986. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20987. var pickedPoint = worldOrigin.add(worldDirection);
  20988. // Return result
  20989. pickingInfo.hit = true;
  20990. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20991. pickingInfo.pickedPoint = pickedPoint;
  20992. pickingInfo.pickedMesh = this;
  20993. pickingInfo.bu = intersectInfo.bu || 0;
  20994. pickingInfo.bv = intersectInfo.bv || 0;
  20995. pickingInfo.faceId = intersectInfo.faceId;
  20996. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20997. return pickingInfo;
  20998. }
  20999. return pickingInfo;
  21000. };
  21001. /**
  21002. * Clones the current mesh
  21003. * @param name defines the mesh name
  21004. * @param newParent defines the new mesh parent
  21005. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21006. * @returns the new mesh
  21007. */
  21008. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21009. return null;
  21010. };
  21011. /**
  21012. * Disposes all the submeshes of the current meshnp
  21013. * @returns the current mesh
  21014. */
  21015. AbstractMesh.prototype.releaseSubMeshes = function () {
  21016. if (this.subMeshes) {
  21017. while (this.subMeshes.length) {
  21018. this.subMeshes[0].dispose();
  21019. }
  21020. }
  21021. else {
  21022. this.subMeshes = new Array();
  21023. }
  21024. return this;
  21025. };
  21026. /**
  21027. * Releases resources associated with this abstract mesh.
  21028. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21029. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21030. */
  21031. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21032. var _this = this;
  21033. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21034. var index;
  21035. // Smart Array Retainers.
  21036. this.getScene().freeActiveMeshes();
  21037. this.getScene().freeRenderingGroups();
  21038. // Action manager
  21039. if (this.actionManager !== undefined && this.actionManager !== null) {
  21040. this.actionManager.dispose();
  21041. this.actionManager = null;
  21042. }
  21043. // Skeleton
  21044. this._skeleton = null;
  21045. // Physics
  21046. if (this.physicsImpostor) {
  21047. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21048. }
  21049. // Intersections in progress
  21050. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21051. var other = this._intersectionsInProgress[index];
  21052. var pos = other._intersectionsInProgress.indexOf(this);
  21053. other._intersectionsInProgress.splice(pos, 1);
  21054. }
  21055. this._intersectionsInProgress = [];
  21056. // Lights
  21057. var lights = this.getScene().lights;
  21058. lights.forEach(function (light) {
  21059. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21060. if (meshIndex !== -1) {
  21061. light.includedOnlyMeshes.splice(meshIndex, 1);
  21062. }
  21063. meshIndex = light.excludedMeshes.indexOf(_this);
  21064. if (meshIndex !== -1) {
  21065. light.excludedMeshes.splice(meshIndex, 1);
  21066. }
  21067. // Shadow generators
  21068. var generator = light.getShadowGenerator();
  21069. if (generator) {
  21070. var shadowMap = generator.getShadowMap();
  21071. if (shadowMap && shadowMap.renderList) {
  21072. meshIndex = shadowMap.renderList.indexOf(_this);
  21073. if (meshIndex !== -1) {
  21074. shadowMap.renderList.splice(meshIndex, 1);
  21075. }
  21076. }
  21077. }
  21078. });
  21079. // Edges
  21080. if (this._edgesRenderer) {
  21081. this._edgesRenderer.dispose();
  21082. this._edgesRenderer = null;
  21083. }
  21084. // SubMeshes
  21085. if (this.getClassName() !== "InstancedMesh") {
  21086. this.releaseSubMeshes();
  21087. }
  21088. // Octree
  21089. var sceneOctree = this.getScene().selectionOctree;
  21090. if (sceneOctree !== undefined && sceneOctree !== null) {
  21091. var index = sceneOctree.dynamicContent.indexOf(this);
  21092. if (index !== -1) {
  21093. sceneOctree.dynamicContent.splice(index, 1);
  21094. }
  21095. }
  21096. // Query
  21097. var engine = this.getScene().getEngine();
  21098. if (this._occlusionQuery) {
  21099. this._isOcclusionQueryInProgress = false;
  21100. engine.deleteQuery(this._occlusionQuery);
  21101. this._occlusionQuery = null;
  21102. }
  21103. // Engine
  21104. engine.wipeCaches();
  21105. // Remove from scene
  21106. this.getScene().removeMesh(this);
  21107. if (disposeMaterialAndTextures) {
  21108. if (this.material) {
  21109. this.material.dispose(false, true);
  21110. }
  21111. }
  21112. if (!doNotRecurse) {
  21113. // Particles
  21114. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21115. if (this.getScene().particleSystems[index].emitter === this) {
  21116. this.getScene().particleSystems[index].dispose();
  21117. index--;
  21118. }
  21119. }
  21120. }
  21121. // facet data
  21122. if (this._facetDataEnabled) {
  21123. this.disableFacetData();
  21124. }
  21125. this.onAfterWorldMatrixUpdateObservable.clear();
  21126. this.onCollideObservable.clear();
  21127. this.onCollisionPositionChangeObservable.clear();
  21128. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21129. };
  21130. /**
  21131. * Adds the passed mesh as a child to the current mesh
  21132. * @param mesh defines the child mesh
  21133. * @returns the current mesh
  21134. */
  21135. AbstractMesh.prototype.addChild = function (mesh) {
  21136. mesh.setParent(this);
  21137. return this;
  21138. };
  21139. /**
  21140. * Removes the passed mesh from the current mesh children list
  21141. * @param mesh defines the child mesh
  21142. * @returns the current mesh
  21143. */
  21144. AbstractMesh.prototype.removeChild = function (mesh) {
  21145. mesh.setParent(null);
  21146. return this;
  21147. };
  21148. // Facet data
  21149. /** @hidden */
  21150. AbstractMesh.prototype._initFacetData = function () {
  21151. if (!this._facetNormals) {
  21152. this._facetNormals = new Array();
  21153. }
  21154. if (!this._facetPositions) {
  21155. this._facetPositions = new Array();
  21156. }
  21157. if (!this._facetPartitioning) {
  21158. this._facetPartitioning = new Array();
  21159. }
  21160. this._facetNb = (this.getIndices().length / 3) | 0;
  21161. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21162. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21163. for (var f = 0; f < this._facetNb; f++) {
  21164. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21165. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21166. }
  21167. this._facetDataEnabled = true;
  21168. return this;
  21169. };
  21170. /**
  21171. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21172. * This method can be called within the render loop.
  21173. * 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
  21174. * @returns the current mesh
  21175. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21176. */
  21177. AbstractMesh.prototype.updateFacetData = function () {
  21178. if (!this._facetDataEnabled) {
  21179. this._initFacetData();
  21180. }
  21181. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21182. var indices = this.getIndices();
  21183. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21184. var bInfo = this.getBoundingInfo();
  21185. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21186. // init arrays, matrix and sort function on first call
  21187. this._facetDepthSortEnabled = true;
  21188. if (indices instanceof Uint16Array) {
  21189. this._depthSortedIndices = new Uint16Array(indices);
  21190. }
  21191. else if (indices instanceof Uint32Array) {
  21192. this._depthSortedIndices = new Uint32Array(indices);
  21193. }
  21194. else {
  21195. var needs32bits = false;
  21196. for (var i = 0; i < indices.length; i++) {
  21197. if (indices[i] > 65535) {
  21198. needs32bits = true;
  21199. break;
  21200. }
  21201. }
  21202. if (needs32bits) {
  21203. this._depthSortedIndices = new Uint32Array(indices);
  21204. }
  21205. else {
  21206. this._depthSortedIndices = new Uint16Array(indices);
  21207. }
  21208. }
  21209. this._facetDepthSortFunction = function (f1, f2) {
  21210. return (f2.sqDistance - f1.sqDistance);
  21211. };
  21212. if (!this._facetDepthSortFrom) {
  21213. var camera = this.getScene().activeCamera;
  21214. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21215. }
  21216. this._depthSortedFacets = [];
  21217. for (var f = 0; f < this._facetNb; f++) {
  21218. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21219. this._depthSortedFacets.push(depthSortedFacet);
  21220. }
  21221. this._invertedMatrix = BABYLON.Matrix.Identity();
  21222. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21223. }
  21224. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21225. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21226. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21227. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21228. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21229. this._subDiv.max = this._partitioningSubdivisions;
  21230. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21231. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21232. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21233. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21234. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21235. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21236. // set the parameters for ComputeNormals()
  21237. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21238. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21239. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21240. this._facetParameters.bInfo = bInfo;
  21241. this._facetParameters.bbSize = this._bbSize;
  21242. this._facetParameters.subDiv = this._subDiv;
  21243. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21244. this._facetParameters.depthSort = this._facetDepthSort;
  21245. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21246. this.computeWorldMatrix(true);
  21247. this._worldMatrix.invertToRef(this._invertedMatrix);
  21248. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21249. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21250. }
  21251. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21252. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21253. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21254. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21255. var l = (this._depthSortedIndices.length / 3) | 0;
  21256. for (var f = 0; f < l; f++) {
  21257. var sind = this._depthSortedFacets[f].ind;
  21258. this._depthSortedIndices[f * 3] = indices[sind];
  21259. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21260. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21261. }
  21262. this.updateIndices(this._depthSortedIndices);
  21263. }
  21264. return this;
  21265. };
  21266. /**
  21267. * Returns the facetLocalNormals array.
  21268. * The normals are expressed in the mesh local spac
  21269. * @returns an array of Vector3
  21270. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21271. */
  21272. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21273. if (!this._facetNormals) {
  21274. this.updateFacetData();
  21275. }
  21276. return this._facetNormals;
  21277. };
  21278. /**
  21279. * Returns the facetLocalPositions array.
  21280. * The facet positions are expressed in the mesh local space
  21281. * @returns an array of Vector3
  21282. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21283. */
  21284. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21285. if (!this._facetPositions) {
  21286. this.updateFacetData();
  21287. }
  21288. return this._facetPositions;
  21289. };
  21290. /**
  21291. * Returns the facetLocalPartioning array
  21292. * @returns an array of array of numbers
  21293. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21294. */
  21295. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21296. if (!this._facetPartitioning) {
  21297. this.updateFacetData();
  21298. }
  21299. return this._facetPartitioning;
  21300. };
  21301. /**
  21302. * Returns the i-th facet position in the world system.
  21303. * This method allocates a new Vector3 per call
  21304. * @param i defines the facet index
  21305. * @returns a new Vector3
  21306. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21307. */
  21308. AbstractMesh.prototype.getFacetPosition = function (i) {
  21309. var pos = BABYLON.Vector3.Zero();
  21310. this.getFacetPositionToRef(i, pos);
  21311. return pos;
  21312. };
  21313. /**
  21314. * Sets the reference Vector3 with the i-th facet position in the world system
  21315. * @param i defines the facet index
  21316. * @param ref defines the target vector
  21317. * @returns the current mesh
  21318. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21319. */
  21320. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21321. var localPos = (this.getFacetLocalPositions())[i];
  21322. var world = this.getWorldMatrix();
  21323. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21324. return this;
  21325. };
  21326. /**
  21327. * Returns the i-th facet normal in the world system.
  21328. * This method allocates a new Vector3 per call
  21329. * @param i defines the facet index
  21330. * @returns a new Vector3
  21331. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21332. */
  21333. AbstractMesh.prototype.getFacetNormal = function (i) {
  21334. var norm = BABYLON.Vector3.Zero();
  21335. this.getFacetNormalToRef(i, norm);
  21336. return norm;
  21337. };
  21338. /**
  21339. * Sets the reference Vector3 with the i-th facet normal in the world system
  21340. * @param i defines the facet index
  21341. * @param ref defines the target vector
  21342. * @returns the current mesh
  21343. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21344. */
  21345. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21346. var localNorm = (this.getFacetLocalNormals())[i];
  21347. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21348. return this;
  21349. };
  21350. /**
  21351. * 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)
  21352. * @param x defines x coordinate
  21353. * @param y defines y coordinate
  21354. * @param z defines z coordinate
  21355. * @returns the array of facet indexes
  21356. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21357. */
  21358. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21359. var bInfo = this.getBoundingInfo();
  21360. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21361. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21362. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21363. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21364. return null;
  21365. }
  21366. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21367. };
  21368. /**
  21369. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21370. * @param projected sets as the (x,y,z) world projection on the facet
  21371. * @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
  21372. * @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
  21373. * @param x defines x coordinate
  21374. * @param y defines y coordinate
  21375. * @param z defines z coordinate
  21376. * @returns the face index if found (or null instead)
  21377. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21378. */
  21379. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21380. if (checkFace === void 0) { checkFace = false; }
  21381. if (facing === void 0) { facing = true; }
  21382. var world = this.getWorldMatrix();
  21383. var invMat = BABYLON.Tmp.Matrix[5];
  21384. world.invertToRef(invMat);
  21385. var invVect = BABYLON.Tmp.Vector3[8];
  21386. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21387. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21388. if (projected) {
  21389. // tranform the local computed projected vector to world coordinates
  21390. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21391. }
  21392. return closest;
  21393. };
  21394. /**
  21395. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21396. * @param projected sets as the (x,y,z) local projection on the facet
  21397. * @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
  21398. * @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
  21399. * @param x defines x coordinate
  21400. * @param y defines y coordinate
  21401. * @param z defines z coordinate
  21402. * @returns the face index if found (or null instead)
  21403. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21404. */
  21405. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21406. if (checkFace === void 0) { checkFace = false; }
  21407. if (facing === void 0) { facing = true; }
  21408. var closest = null;
  21409. var tmpx = 0.0;
  21410. var tmpy = 0.0;
  21411. var tmpz = 0.0;
  21412. var d = 0.0; // tmp dot facet normal * facet position
  21413. var t0 = 0.0;
  21414. var projx = 0.0;
  21415. var projy = 0.0;
  21416. var projz = 0.0;
  21417. // Get all the facets in the same partitioning block than (x, y, z)
  21418. var facetPositions = this.getFacetLocalPositions();
  21419. var facetNormals = this.getFacetLocalNormals();
  21420. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21421. if (!facetsInBlock) {
  21422. return null;
  21423. }
  21424. // Get the closest facet to (x, y, z)
  21425. var shortest = Number.MAX_VALUE; // init distance vars
  21426. var tmpDistance = shortest;
  21427. var fib; // current facet in the block
  21428. var norm; // current facet normal
  21429. var p0; // current facet barycenter position
  21430. // loop on all the facets in the current partitioning block
  21431. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21432. fib = facetsInBlock[idx];
  21433. norm = facetNormals[fib];
  21434. p0 = facetPositions[fib];
  21435. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21436. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21437. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21438. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21439. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21440. projx = x + norm.x * t0;
  21441. projy = y + norm.y * t0;
  21442. projz = z + norm.z * t0;
  21443. tmpx = projx - x;
  21444. tmpy = projy - y;
  21445. tmpz = projz - z;
  21446. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21447. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21448. shortest = tmpDistance;
  21449. closest = fib;
  21450. if (projected) {
  21451. projected.x = projx;
  21452. projected.y = projy;
  21453. projected.z = projz;
  21454. }
  21455. }
  21456. }
  21457. }
  21458. return closest;
  21459. };
  21460. /**
  21461. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21462. * @returns the parameters
  21463. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21464. */
  21465. AbstractMesh.prototype.getFacetDataParameters = function () {
  21466. return this._facetParameters;
  21467. };
  21468. /**
  21469. * Disables the feature FacetData and frees the related memory
  21470. * @returns the current mesh
  21471. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21472. */
  21473. AbstractMesh.prototype.disableFacetData = function () {
  21474. if (this._facetDataEnabled) {
  21475. this._facetDataEnabled = false;
  21476. this._facetPositions = new Array();
  21477. this._facetNormals = new Array();
  21478. this._facetPartitioning = new Array();
  21479. this._facetParameters = null;
  21480. this._depthSortedIndices = new Uint32Array(0);
  21481. }
  21482. return this;
  21483. };
  21484. /**
  21485. * Updates the AbstractMesh indices array
  21486. * @param indices defines the data source
  21487. * @returns the current mesh
  21488. */
  21489. AbstractMesh.prototype.updateIndices = function (indices) {
  21490. return this;
  21491. };
  21492. /**
  21493. * Creates new normals data for the mesh
  21494. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21495. * @returns the current mesh
  21496. */
  21497. AbstractMesh.prototype.createNormals = function (updatable) {
  21498. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21499. var indices = this.getIndices();
  21500. var normals;
  21501. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21502. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21503. }
  21504. else {
  21505. normals = [];
  21506. }
  21507. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21508. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21509. return this;
  21510. };
  21511. /**
  21512. * Align the mesh with a normal
  21513. * @param normal defines the normal to use
  21514. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21515. * @returns the current mesh
  21516. */
  21517. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21518. if (!upDirection) {
  21519. upDirection = BABYLON.Axis.Y;
  21520. }
  21521. var axisX = BABYLON.Tmp.Vector3[0];
  21522. var axisZ = BABYLON.Tmp.Vector3[1];
  21523. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21524. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21525. if (this.rotationQuaternion) {
  21526. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21527. }
  21528. else {
  21529. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21530. }
  21531. return this;
  21532. };
  21533. /** @hidden */
  21534. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21535. var engine = this.getEngine();
  21536. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21537. this._isOccluded = false;
  21538. return;
  21539. }
  21540. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21541. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21542. if (isOcclusionQueryAvailable) {
  21543. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21544. this._isOcclusionQueryInProgress = false;
  21545. this._occlusionInternalRetryCounter = 0;
  21546. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21547. }
  21548. else {
  21549. this._occlusionInternalRetryCounter++;
  21550. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21551. this._isOcclusionQueryInProgress = false;
  21552. this._occlusionInternalRetryCounter = 0;
  21553. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21554. // if strict continue the last state of the object.
  21555. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21556. }
  21557. else {
  21558. return;
  21559. }
  21560. }
  21561. }
  21562. var scene = this.getScene();
  21563. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21564. if (!this._occlusionQuery) {
  21565. this._occlusionQuery = engine.createQuery();
  21566. }
  21567. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21568. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21569. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21570. this._isOcclusionQueryInProgress = true;
  21571. };
  21572. /** No occlusion */
  21573. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21574. /** Occlusion set to optimisitic */
  21575. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21576. /** Occlusion set to strict */
  21577. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21578. /** Use an accurante occlusion algorithm */
  21579. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21580. /** Use a conservative occlusion algorithm */
  21581. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21582. return AbstractMesh;
  21583. }(BABYLON.TransformNode));
  21584. BABYLON.AbstractMesh = AbstractMesh;
  21585. })(BABYLON || (BABYLON = {}));
  21586. //# sourceMappingURL=babylon.abstractMesh.js.map
  21587. var BABYLON;
  21588. (function (BABYLON) {
  21589. /**
  21590. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21591. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21592. * 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.
  21593. */
  21594. var Light = /** @class */ (function (_super) {
  21595. __extends(Light, _super);
  21596. /**
  21597. * Creates a Light object in the scene.
  21598. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21599. * @param name The firendly name of the light
  21600. * @param scene The scene the light belongs too
  21601. */
  21602. function Light(name, scene) {
  21603. var _this = _super.call(this, name, scene) || this;
  21604. /**
  21605. * Diffuse gives the basic color to an object.
  21606. */
  21607. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21608. /**
  21609. * Specular produces a highlight color on an object.
  21610. * Note: This is note affecting PBR materials.
  21611. */
  21612. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21613. /**
  21614. * Strength of the light.
  21615. * Note: By default it is define in the framework own unit.
  21616. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21617. */
  21618. _this.intensity = 1.0;
  21619. /**
  21620. * Defines how far from the source the light is impacting in scene units.
  21621. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21622. */
  21623. _this.range = Number.MAX_VALUE;
  21624. /**
  21625. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21626. * of light.
  21627. */
  21628. _this._photometricScale = 1.0;
  21629. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21630. _this._radius = 0.00001;
  21631. /**
  21632. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21633. * exceeding the number allowed of the materials.
  21634. */
  21635. _this.renderPriority = 0;
  21636. _this._shadowEnabled = true;
  21637. _this._excludeWithLayerMask = 0;
  21638. _this._includeOnlyWithLayerMask = 0;
  21639. _this._lightmapMode = 0;
  21640. /**
  21641. * @hidden Internal use only.
  21642. */
  21643. _this._excludedMeshesIds = new Array();
  21644. /**
  21645. * @hidden Internal use only.
  21646. */
  21647. _this._includedOnlyMeshesIds = new Array();
  21648. _this.getScene().addLight(_this);
  21649. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21650. _this._buildUniformLayout();
  21651. _this.includedOnlyMeshes = new Array();
  21652. _this.excludedMeshes = new Array();
  21653. _this._resyncMeshes();
  21654. return _this;
  21655. }
  21656. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21657. /**
  21658. * If every light affecting the material is in this lightmapMode,
  21659. * material.lightmapTexture adds or multiplies
  21660. * (depends on material.useLightmapAsShadowmap)
  21661. * after every other light calculations.
  21662. */
  21663. get: function () {
  21664. return Light._LIGHTMAP_DEFAULT;
  21665. },
  21666. enumerable: true,
  21667. configurable: true
  21668. });
  21669. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21670. /**
  21671. * material.lightmapTexture as only diffuse lighting from this light
  21672. * adds only specular lighting from this light
  21673. * adds dynamic shadows
  21674. */
  21675. get: function () {
  21676. return Light._LIGHTMAP_SPECULAR;
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21682. /**
  21683. * material.lightmapTexture as only lighting
  21684. * no light calculation from this light
  21685. * only adds dynamic shadows from this light
  21686. */
  21687. get: function () {
  21688. return Light._LIGHTMAP_SHADOWSONLY;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21694. /**
  21695. * Each light type uses the default quantity according to its type:
  21696. * point/spot lights use luminous intensity
  21697. * directional lights use illuminance
  21698. */
  21699. get: function () {
  21700. return Light._INTENSITYMODE_AUTOMATIC;
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21706. /**
  21707. * lumen (lm)
  21708. */
  21709. get: function () {
  21710. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21711. },
  21712. enumerable: true,
  21713. configurable: true
  21714. });
  21715. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21716. /**
  21717. * candela (lm/sr)
  21718. */
  21719. get: function () {
  21720. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21726. /**
  21727. * lux (lm/m^2)
  21728. */
  21729. get: function () {
  21730. return Light._INTENSITYMODE_ILLUMINANCE;
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21736. /**
  21737. * nit (cd/m^2)
  21738. */
  21739. get: function () {
  21740. return Light._INTENSITYMODE_LUMINANCE;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21746. /**
  21747. * Light type const id of the point light.
  21748. */
  21749. get: function () {
  21750. return Light._LIGHTTYPEID_POINTLIGHT;
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21756. /**
  21757. * Light type const id of the directional light.
  21758. */
  21759. get: function () {
  21760. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21766. /**
  21767. * Light type const id of the spot light.
  21768. */
  21769. get: function () {
  21770. return Light._LIGHTTYPEID_SPOTLIGHT;
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21776. /**
  21777. * Light type const id of the hemispheric light.
  21778. */
  21779. get: function () {
  21780. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21781. },
  21782. enumerable: true,
  21783. configurable: true
  21784. });
  21785. Object.defineProperty(Light.prototype, "intensityMode", {
  21786. /**
  21787. * Gets the photometric scale used to interpret the intensity.
  21788. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21789. */
  21790. get: function () {
  21791. return this._intensityMode;
  21792. },
  21793. /**
  21794. * Sets the photometric scale used to interpret the intensity.
  21795. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21796. */
  21797. set: function (value) {
  21798. this._intensityMode = value;
  21799. this._computePhotometricScale();
  21800. },
  21801. enumerable: true,
  21802. configurable: true
  21803. });
  21804. ;
  21805. ;
  21806. Object.defineProperty(Light.prototype, "radius", {
  21807. /**
  21808. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21809. */
  21810. get: function () {
  21811. return this._radius;
  21812. },
  21813. /**
  21814. * sets the light radius used by PBR Materials to simulate soft area lights.
  21815. */
  21816. set: function (value) {
  21817. this._radius = value;
  21818. this._computePhotometricScale();
  21819. },
  21820. enumerable: true,
  21821. configurable: true
  21822. });
  21823. ;
  21824. ;
  21825. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21826. /**
  21827. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21828. * the current shadow generator.
  21829. */
  21830. get: function () {
  21831. return this._shadowEnabled;
  21832. },
  21833. /**
  21834. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21835. * the current shadow generator.
  21836. */
  21837. set: function (value) {
  21838. if (this._shadowEnabled === value) {
  21839. return;
  21840. }
  21841. this._shadowEnabled = value;
  21842. this._markMeshesAsLightDirty();
  21843. },
  21844. enumerable: true,
  21845. configurable: true
  21846. });
  21847. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21848. /**
  21849. * Gets the only meshes impacted by this light.
  21850. */
  21851. get: function () {
  21852. return this._includedOnlyMeshes;
  21853. },
  21854. /**
  21855. * Sets the only meshes impacted by this light.
  21856. */
  21857. set: function (value) {
  21858. this._includedOnlyMeshes = value;
  21859. this._hookArrayForIncludedOnly(value);
  21860. },
  21861. enumerable: true,
  21862. configurable: true
  21863. });
  21864. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21865. /**
  21866. * Gets the meshes not impacted by this light.
  21867. */
  21868. get: function () {
  21869. return this._excludedMeshes;
  21870. },
  21871. /**
  21872. * Sets the meshes not impacted by this light.
  21873. */
  21874. set: function (value) {
  21875. this._excludedMeshes = value;
  21876. this._hookArrayForExcluded(value);
  21877. },
  21878. enumerable: true,
  21879. configurable: true
  21880. });
  21881. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21882. /**
  21883. * Gets the layer id use to find what meshes are not impacted by the light.
  21884. * Inactive if 0
  21885. */
  21886. get: function () {
  21887. return this._excludeWithLayerMask;
  21888. },
  21889. /**
  21890. * Sets the layer id use to find what meshes are not impacted by the light.
  21891. * Inactive if 0
  21892. */
  21893. set: function (value) {
  21894. this._excludeWithLayerMask = value;
  21895. this._resyncMeshes();
  21896. },
  21897. enumerable: true,
  21898. configurable: true
  21899. });
  21900. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21901. /**
  21902. * Gets the layer id use to find what meshes are impacted by the light.
  21903. * Inactive if 0
  21904. */
  21905. get: function () {
  21906. return this._includeOnlyWithLayerMask;
  21907. },
  21908. /**
  21909. * Sets the layer id use to find what meshes are impacted by the light.
  21910. * Inactive if 0
  21911. */
  21912. set: function (value) {
  21913. this._includeOnlyWithLayerMask = value;
  21914. this._resyncMeshes();
  21915. },
  21916. enumerable: true,
  21917. configurable: true
  21918. });
  21919. Object.defineProperty(Light.prototype, "lightmapMode", {
  21920. /**
  21921. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21922. */
  21923. get: function () {
  21924. return this._lightmapMode;
  21925. },
  21926. /**
  21927. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21928. */
  21929. set: function (value) {
  21930. if (this._lightmapMode === value) {
  21931. return;
  21932. }
  21933. this._lightmapMode = value;
  21934. this._markMeshesAsLightDirty();
  21935. },
  21936. enumerable: true,
  21937. configurable: true
  21938. });
  21939. /**
  21940. * Returns the string "Light".
  21941. * @returns the class name
  21942. */
  21943. Light.prototype.getClassName = function () {
  21944. return "Light";
  21945. };
  21946. /**
  21947. * Converts the light information to a readable string for debug purpose.
  21948. * @param fullDetails Supports for multiple levels of logging within scene loading
  21949. * @returns the human readable light info
  21950. */
  21951. Light.prototype.toString = function (fullDetails) {
  21952. var ret = "Name: " + this.name;
  21953. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21954. if (this.animations) {
  21955. for (var i = 0; i < this.animations.length; i++) {
  21956. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21957. }
  21958. }
  21959. if (fullDetails) {
  21960. }
  21961. return ret;
  21962. };
  21963. /**
  21964. * Set the enabled state of this node.
  21965. * @param value - the new enabled state
  21966. */
  21967. Light.prototype.setEnabled = function (value) {
  21968. _super.prototype.setEnabled.call(this, value);
  21969. this._resyncMeshes();
  21970. };
  21971. /**
  21972. * Returns the Light associated shadow generator if any.
  21973. * @return the associated shadow generator.
  21974. */
  21975. Light.prototype.getShadowGenerator = function () {
  21976. return this._shadowGenerator;
  21977. };
  21978. /**
  21979. * Returns a Vector3, the absolute light position in the World.
  21980. * @returns the world space position of the light
  21981. */
  21982. Light.prototype.getAbsolutePosition = function () {
  21983. return BABYLON.Vector3.Zero();
  21984. };
  21985. /**
  21986. * Specifies if the light will affect the passed mesh.
  21987. * @param mesh The mesh to test against the light
  21988. * @return true the mesh is affected otherwise, false.
  21989. */
  21990. Light.prototype.canAffectMesh = function (mesh) {
  21991. if (!mesh) {
  21992. return true;
  21993. }
  21994. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21995. return false;
  21996. }
  21997. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21998. return false;
  21999. }
  22000. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22001. return false;
  22002. }
  22003. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22004. return false;
  22005. }
  22006. return true;
  22007. };
  22008. /**
  22009. * Computes and Returns the light World matrix.
  22010. * @returns the world matrix
  22011. */
  22012. Light.prototype.getWorldMatrix = function () {
  22013. this._currentRenderId = this.getScene().getRenderId();
  22014. this._childRenderId = this._currentRenderId;
  22015. var worldMatrix = this._getWorldMatrix();
  22016. if (this.parent && this.parent.getWorldMatrix) {
  22017. if (!this._parentedWorldMatrix) {
  22018. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  22019. }
  22020. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  22021. this._markSyncedWithParent();
  22022. return this._parentedWorldMatrix;
  22023. }
  22024. return worldMatrix;
  22025. };
  22026. /**
  22027. * Sort function to order lights for rendering.
  22028. * @param a First Light object to compare to second.
  22029. * @param b Second Light object to compare first.
  22030. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22031. */
  22032. Light.CompareLightsPriority = function (a, b) {
  22033. //shadow-casting lights have priority over non-shadow-casting lights
  22034. //the renderPrioirty is a secondary sort criterion
  22035. if (a.shadowEnabled !== b.shadowEnabled) {
  22036. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22037. }
  22038. return b.renderPriority - a.renderPriority;
  22039. };
  22040. /**
  22041. * Releases resources associated with this node.
  22042. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22043. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22044. */
  22045. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22046. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22047. if (this._shadowGenerator) {
  22048. this._shadowGenerator.dispose();
  22049. this._shadowGenerator = null;
  22050. }
  22051. // Animations
  22052. this.getScene().stopAnimation(this);
  22053. // Remove from meshes
  22054. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22055. var mesh = _a[_i];
  22056. mesh._removeLightSource(this);
  22057. }
  22058. this._uniformBuffer.dispose();
  22059. // Remove from scene
  22060. this.getScene().removeLight(this);
  22061. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22062. };
  22063. /**
  22064. * Returns the light type ID (integer).
  22065. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22066. */
  22067. Light.prototype.getTypeID = function () {
  22068. return 0;
  22069. };
  22070. /**
  22071. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22072. * @returns the scaled intensity in intensity mode unit
  22073. */
  22074. Light.prototype.getScaledIntensity = function () {
  22075. return this._photometricScale * this.intensity;
  22076. };
  22077. /**
  22078. * Returns a new Light object, named "name", from the current one.
  22079. * @param name The name of the cloned light
  22080. * @returns the new created light
  22081. */
  22082. Light.prototype.clone = function (name) {
  22083. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22084. if (!constructor) {
  22085. return null;
  22086. }
  22087. return BABYLON.SerializationHelper.Clone(constructor, this);
  22088. };
  22089. /**
  22090. * Serializes the current light into a Serialization object.
  22091. * @returns the serialized object.
  22092. */
  22093. Light.prototype.serialize = function () {
  22094. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22095. // Type
  22096. serializationObject.type = this.getTypeID();
  22097. // Parent
  22098. if (this.parent) {
  22099. serializationObject.parentId = this.parent.id;
  22100. }
  22101. // Inclusion / exclusions
  22102. if (this.excludedMeshes.length > 0) {
  22103. serializationObject.excludedMeshesIds = [];
  22104. this.excludedMeshes.forEach(function (mesh) {
  22105. serializationObject.excludedMeshesIds.push(mesh.id);
  22106. });
  22107. }
  22108. if (this.includedOnlyMeshes.length > 0) {
  22109. serializationObject.includedOnlyMeshesIds = [];
  22110. this.includedOnlyMeshes.forEach(function (mesh) {
  22111. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22112. });
  22113. }
  22114. // Animations
  22115. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22116. serializationObject.ranges = this.serializeAnimationRanges();
  22117. return serializationObject;
  22118. };
  22119. /**
  22120. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22121. * This new light is named "name" and added to the passed scene.
  22122. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22123. * @param name The friendly name of the light
  22124. * @param scene The scene the new light will belong to
  22125. * @returns the constructor function
  22126. */
  22127. Light.GetConstructorFromName = function (type, name, scene) {
  22128. switch (type) {
  22129. case 0:
  22130. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22131. case 1:
  22132. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22133. case 2:
  22134. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22135. case 3:
  22136. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22137. }
  22138. return null;
  22139. };
  22140. /**
  22141. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22142. * @param parsedLight The JSON representation of the light
  22143. * @param scene The scene to create the parsed light in
  22144. * @returns the created light after parsing
  22145. */
  22146. Light.Parse = function (parsedLight, scene) {
  22147. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22148. if (!constructor) {
  22149. return null;
  22150. }
  22151. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22152. // Inclusion / exclusions
  22153. if (parsedLight.excludedMeshesIds) {
  22154. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22155. }
  22156. if (parsedLight.includedOnlyMeshesIds) {
  22157. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22158. }
  22159. // Parent
  22160. if (parsedLight.parentId) {
  22161. light._waitingParentId = parsedLight.parentId;
  22162. }
  22163. // Animations
  22164. if (parsedLight.animations) {
  22165. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22166. var parsedAnimation = parsedLight.animations[animationIndex];
  22167. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22168. }
  22169. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22170. }
  22171. if (parsedLight.autoAnimate) {
  22172. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22173. }
  22174. return light;
  22175. };
  22176. Light.prototype._hookArrayForExcluded = function (array) {
  22177. var _this = this;
  22178. var oldPush = array.push;
  22179. array.push = function () {
  22180. var items = [];
  22181. for (var _i = 0; _i < arguments.length; _i++) {
  22182. items[_i] = arguments[_i];
  22183. }
  22184. var result = oldPush.apply(array, items);
  22185. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22186. var item = items_1[_a];
  22187. item._resyncLighSource(_this);
  22188. }
  22189. return result;
  22190. };
  22191. var oldSplice = array.splice;
  22192. array.splice = function (index, deleteCount) {
  22193. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22194. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22195. var item = deleted_1[_i];
  22196. item._resyncLighSource(_this);
  22197. }
  22198. return deleted;
  22199. };
  22200. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22201. var item = array_1[_i];
  22202. item._resyncLighSource(this);
  22203. }
  22204. };
  22205. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22206. var _this = this;
  22207. var oldPush = array.push;
  22208. array.push = function () {
  22209. var items = [];
  22210. for (var _i = 0; _i < arguments.length; _i++) {
  22211. items[_i] = arguments[_i];
  22212. }
  22213. var result = oldPush.apply(array, items);
  22214. _this._resyncMeshes();
  22215. return result;
  22216. };
  22217. var oldSplice = array.splice;
  22218. array.splice = function (index, deleteCount) {
  22219. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22220. _this._resyncMeshes();
  22221. return deleted;
  22222. };
  22223. this._resyncMeshes();
  22224. };
  22225. Light.prototype._resyncMeshes = function () {
  22226. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22227. var mesh = _a[_i];
  22228. mesh._resyncLighSource(this);
  22229. }
  22230. };
  22231. /**
  22232. * Forces the meshes to update their light related information in their rendering used effects
  22233. * @hidden Internal Use Only
  22234. */
  22235. Light.prototype._markMeshesAsLightDirty = function () {
  22236. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22237. var mesh = _a[_i];
  22238. if (mesh._lightSources.indexOf(this) !== -1) {
  22239. mesh._markSubMeshesAsLightDirty();
  22240. }
  22241. }
  22242. };
  22243. /**
  22244. * Recomputes the cached photometric scale if needed.
  22245. */
  22246. Light.prototype._computePhotometricScale = function () {
  22247. this._photometricScale = this._getPhotometricScale();
  22248. this.getScene().resetCachedMaterial();
  22249. };
  22250. /**
  22251. * Returns the Photometric Scale according to the light type and intensity mode.
  22252. */
  22253. Light.prototype._getPhotometricScale = function () {
  22254. var photometricScale = 0.0;
  22255. var lightTypeID = this.getTypeID();
  22256. //get photometric mode
  22257. var photometricMode = this.intensityMode;
  22258. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22259. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22260. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22261. }
  22262. else {
  22263. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22264. }
  22265. }
  22266. //compute photometric scale
  22267. switch (lightTypeID) {
  22268. case Light.LIGHTTYPEID_POINTLIGHT:
  22269. case Light.LIGHTTYPEID_SPOTLIGHT:
  22270. switch (photometricMode) {
  22271. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22272. photometricScale = 1.0 / (4.0 * Math.PI);
  22273. break;
  22274. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22275. photometricScale = 1.0;
  22276. break;
  22277. case Light.INTENSITYMODE_LUMINANCE:
  22278. photometricScale = this.radius * this.radius;
  22279. break;
  22280. }
  22281. break;
  22282. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22283. switch (photometricMode) {
  22284. case Light.INTENSITYMODE_ILLUMINANCE:
  22285. photometricScale = 1.0;
  22286. break;
  22287. case Light.INTENSITYMODE_LUMINANCE:
  22288. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22289. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22290. var apexAngleRadians = this.radius;
  22291. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22292. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22293. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22294. photometricScale = solidAngle;
  22295. break;
  22296. }
  22297. break;
  22298. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22299. // No fall off in hemisperic light.
  22300. photometricScale = 1.0;
  22301. break;
  22302. }
  22303. return photometricScale;
  22304. };
  22305. /**
  22306. * Reorder the light in the scene according to their defined priority.
  22307. * @hidden Internal Use Only
  22308. */
  22309. Light.prototype._reorderLightsInScene = function () {
  22310. var scene = this.getScene();
  22311. if (this._renderPriority != 0) {
  22312. scene.requireLightSorting = true;
  22313. }
  22314. this.getScene().sortLightsByPriority();
  22315. };
  22316. //lightmapMode Consts
  22317. Light._LIGHTMAP_DEFAULT = 0;
  22318. Light._LIGHTMAP_SPECULAR = 1;
  22319. Light._LIGHTMAP_SHADOWSONLY = 2;
  22320. // Intensity Mode Consts
  22321. Light._INTENSITYMODE_AUTOMATIC = 0;
  22322. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22323. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22324. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22325. Light._INTENSITYMODE_LUMINANCE = 4;
  22326. // Light types ids const.
  22327. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22328. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22329. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22330. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22331. __decorate([
  22332. BABYLON.serializeAsColor3()
  22333. ], Light.prototype, "diffuse", void 0);
  22334. __decorate([
  22335. BABYLON.serializeAsColor3()
  22336. ], Light.prototype, "specular", void 0);
  22337. __decorate([
  22338. BABYLON.serialize()
  22339. ], Light.prototype, "intensity", void 0);
  22340. __decorate([
  22341. BABYLON.serialize()
  22342. ], Light.prototype, "range", void 0);
  22343. __decorate([
  22344. BABYLON.serialize()
  22345. ], Light.prototype, "intensityMode", null);
  22346. __decorate([
  22347. BABYLON.serialize()
  22348. ], Light.prototype, "radius", null);
  22349. __decorate([
  22350. BABYLON.serialize()
  22351. ], Light.prototype, "_renderPriority", void 0);
  22352. __decorate([
  22353. BABYLON.expandToProperty("_reorderLightsInScene")
  22354. ], Light.prototype, "renderPriority", void 0);
  22355. __decorate([
  22356. BABYLON.serialize("shadowEnabled")
  22357. ], Light.prototype, "_shadowEnabled", void 0);
  22358. __decorate([
  22359. BABYLON.serialize("excludeWithLayerMask")
  22360. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22361. __decorate([
  22362. BABYLON.serialize("includeOnlyWithLayerMask")
  22363. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22364. __decorate([
  22365. BABYLON.serialize("lightmapMode")
  22366. ], Light.prototype, "_lightmapMode", void 0);
  22367. return Light;
  22368. }(BABYLON.Node));
  22369. BABYLON.Light = Light;
  22370. })(BABYLON || (BABYLON = {}));
  22371. //# sourceMappingURL=babylon.light.js.map
  22372. var BABYLON;
  22373. (function (BABYLON) {
  22374. var Camera = /** @class */ (function (_super) {
  22375. __extends(Camera, _super);
  22376. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22377. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22378. var _this = _super.call(this, name, scene) || this;
  22379. /**
  22380. * The vector the camera should consider as up.
  22381. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22382. */
  22383. _this.upVector = BABYLON.Vector3.Up();
  22384. _this.orthoLeft = null;
  22385. _this.orthoRight = null;
  22386. _this.orthoBottom = null;
  22387. _this.orthoTop = null;
  22388. /**
  22389. * FOV is set in Radians. (default is 0.8)
  22390. */
  22391. _this.fov = 0.8;
  22392. _this.minZ = 1;
  22393. _this.maxZ = 10000.0;
  22394. _this.inertia = 0.9;
  22395. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22396. _this.isIntermediate = false;
  22397. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22398. /**
  22399. * Restricts the camera to viewing objects with the same layerMask.
  22400. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22401. */
  22402. _this.layerMask = 0x0FFFFFFF;
  22403. /**
  22404. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22405. */
  22406. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22407. // Camera rig members
  22408. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22409. _this._rigCameras = new Array();
  22410. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22411. _this._skipRendering = false;
  22412. _this.customRenderTargets = new Array();
  22413. // Observables
  22414. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22415. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22416. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22417. _this.onRestoreStateObservable = new BABYLON.Observable();
  22418. // Cache
  22419. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22420. _this._projectionMatrix = new BABYLON.Matrix();
  22421. _this._doNotComputeProjectionMatrix = false;
  22422. _this._worldMatrix = BABYLON.Matrix.Identity();
  22423. _this._postProcesses = new Array();
  22424. _this._transformMatrix = BABYLON.Matrix.Zero();
  22425. _this._activeMeshes = new BABYLON.SmartArray(256);
  22426. _this._globalPosition = BABYLON.Vector3.Zero();
  22427. _this._refreshFrustumPlanes = true;
  22428. _this.getScene().addCamera(_this);
  22429. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22430. _this.getScene().activeCamera = _this;
  22431. }
  22432. _this.position = position;
  22433. return _this;
  22434. }
  22435. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22436. get: function () {
  22437. return Camera._PERSPECTIVE_CAMERA;
  22438. },
  22439. enumerable: true,
  22440. configurable: true
  22441. });
  22442. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22443. get: function () {
  22444. return Camera._ORTHOGRAPHIC_CAMERA;
  22445. },
  22446. enumerable: true,
  22447. configurable: true
  22448. });
  22449. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22450. /**
  22451. * This is the default FOV mode for perspective cameras.
  22452. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22453. *
  22454. */
  22455. get: function () {
  22456. return Camera._FOVMODE_VERTICAL_FIXED;
  22457. },
  22458. enumerable: true,
  22459. configurable: true
  22460. });
  22461. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22462. /**
  22463. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22464. *
  22465. */
  22466. get: function () {
  22467. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22468. },
  22469. enumerable: true,
  22470. configurable: true
  22471. });
  22472. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22473. get: function () {
  22474. return Camera._RIG_MODE_NONE;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22480. get: function () {
  22481. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22482. },
  22483. enumerable: true,
  22484. configurable: true
  22485. });
  22486. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22487. get: function () {
  22488. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22494. get: function () {
  22495. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22496. },
  22497. enumerable: true,
  22498. configurable: true
  22499. });
  22500. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22501. get: function () {
  22502. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22503. },
  22504. enumerable: true,
  22505. configurable: true
  22506. });
  22507. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22508. get: function () {
  22509. return Camera._RIG_MODE_VR;
  22510. },
  22511. enumerable: true,
  22512. configurable: true
  22513. });
  22514. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22515. get: function () {
  22516. return Camera._RIG_MODE_WEBVR;
  22517. },
  22518. enumerable: true,
  22519. configurable: true
  22520. });
  22521. /**
  22522. * Store current camera state (fov, position, etc..)
  22523. */
  22524. Camera.prototype.storeState = function () {
  22525. this._stateStored = true;
  22526. this._storedFov = this.fov;
  22527. return this;
  22528. };
  22529. /**
  22530. * Restores the camera state values if it has been stored. You must call storeState() first
  22531. */
  22532. Camera.prototype._restoreStateValues = function () {
  22533. if (!this._stateStored) {
  22534. return false;
  22535. }
  22536. this.fov = this._storedFov;
  22537. return true;
  22538. };
  22539. /**
  22540. * Restored camera state. You must call storeState() first
  22541. */
  22542. Camera.prototype.restoreState = function () {
  22543. if (this._restoreStateValues()) {
  22544. this.onRestoreStateObservable.notifyObservers(this);
  22545. return true;
  22546. }
  22547. return false;
  22548. };
  22549. Camera.prototype.getClassName = function () {
  22550. return "Camera";
  22551. };
  22552. /**
  22553. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22554. */
  22555. Camera.prototype.toString = function (fullDetails) {
  22556. var ret = "Name: " + this.name;
  22557. ret += ", type: " + this.getClassName();
  22558. if (this.animations) {
  22559. for (var i = 0; i < this.animations.length; i++) {
  22560. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22561. }
  22562. }
  22563. if (fullDetails) {
  22564. }
  22565. return ret;
  22566. };
  22567. Object.defineProperty(Camera.prototype, "globalPosition", {
  22568. get: function () {
  22569. return this._globalPosition;
  22570. },
  22571. enumerable: true,
  22572. configurable: true
  22573. });
  22574. Camera.prototype.getActiveMeshes = function () {
  22575. return this._activeMeshes;
  22576. };
  22577. Camera.prototype.isActiveMesh = function (mesh) {
  22578. return (this._activeMeshes.indexOf(mesh) !== -1);
  22579. };
  22580. /**
  22581. * Is this camera ready to be used/rendered
  22582. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22583. * @return true if the camera is ready
  22584. */
  22585. Camera.prototype.isReady = function (completeCheck) {
  22586. if (completeCheck === void 0) { completeCheck = false; }
  22587. if (completeCheck) {
  22588. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22589. var pp = _a[_i];
  22590. if (pp && !pp.isReady()) {
  22591. return false;
  22592. }
  22593. }
  22594. }
  22595. return _super.prototype.isReady.call(this, completeCheck);
  22596. };
  22597. //Cache
  22598. Camera.prototype._initCache = function () {
  22599. _super.prototype._initCache.call(this);
  22600. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22601. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22602. this._cache.mode = undefined;
  22603. this._cache.minZ = undefined;
  22604. this._cache.maxZ = undefined;
  22605. this._cache.fov = undefined;
  22606. this._cache.fovMode = undefined;
  22607. this._cache.aspectRatio = undefined;
  22608. this._cache.orthoLeft = undefined;
  22609. this._cache.orthoRight = undefined;
  22610. this._cache.orthoBottom = undefined;
  22611. this._cache.orthoTop = undefined;
  22612. this._cache.renderWidth = undefined;
  22613. this._cache.renderHeight = undefined;
  22614. };
  22615. Camera.prototype._updateCache = function (ignoreParentClass) {
  22616. if (!ignoreParentClass) {
  22617. _super.prototype._updateCache.call(this);
  22618. }
  22619. this._cache.position.copyFrom(this.position);
  22620. this._cache.upVector.copyFrom(this.upVector);
  22621. };
  22622. // Synchronized
  22623. Camera.prototype._isSynchronized = function () {
  22624. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22625. };
  22626. Camera.prototype._isSynchronizedViewMatrix = function () {
  22627. if (!_super.prototype._isSynchronized.call(this))
  22628. return false;
  22629. return this._cache.position.equals(this.position)
  22630. && this._cache.upVector.equals(this.upVector)
  22631. && this.isSynchronizedWithParent();
  22632. };
  22633. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22634. var check = this._cache.mode === this.mode
  22635. && this._cache.minZ === this.minZ
  22636. && this._cache.maxZ === this.maxZ;
  22637. if (!check) {
  22638. return false;
  22639. }
  22640. var engine = this.getEngine();
  22641. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22642. check = this._cache.fov === this.fov
  22643. && this._cache.fovMode === this.fovMode
  22644. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22645. }
  22646. else {
  22647. check = this._cache.orthoLeft === this.orthoLeft
  22648. && this._cache.orthoRight === this.orthoRight
  22649. && this._cache.orthoBottom === this.orthoBottom
  22650. && this._cache.orthoTop === this.orthoTop
  22651. && this._cache.renderWidth === engine.getRenderWidth()
  22652. && this._cache.renderHeight === engine.getRenderHeight();
  22653. }
  22654. return check;
  22655. };
  22656. // Controls
  22657. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22658. };
  22659. Camera.prototype.detachControl = function (element) {
  22660. };
  22661. Camera.prototype.update = function () {
  22662. this._checkInputs();
  22663. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22664. this._updateRigCameras();
  22665. }
  22666. };
  22667. Camera.prototype._checkInputs = function () {
  22668. this.onAfterCheckInputsObservable.notifyObservers(this);
  22669. };
  22670. Object.defineProperty(Camera.prototype, "rigCameras", {
  22671. get: function () {
  22672. return this._rigCameras;
  22673. },
  22674. enumerable: true,
  22675. configurable: true
  22676. });
  22677. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22678. get: function () {
  22679. return this._rigPostProcess;
  22680. },
  22681. enumerable: true,
  22682. configurable: true
  22683. });
  22684. /**
  22685. * Internal, gets the first post proces.
  22686. * @returns the first post process to be run on this camera.
  22687. */
  22688. Camera.prototype._getFirstPostProcess = function () {
  22689. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22690. if (this._postProcesses[ppIndex] !== null) {
  22691. return this._postProcesses[ppIndex];
  22692. }
  22693. }
  22694. return null;
  22695. };
  22696. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22697. // invalidate framebuffer
  22698. var firstPostProcess = this._getFirstPostProcess();
  22699. if (firstPostProcess) {
  22700. firstPostProcess.markTextureDirty();
  22701. }
  22702. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22703. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22704. var cam = this._rigCameras[i];
  22705. var rigPostProcess = cam._rigPostProcess;
  22706. // for VR rig, there does not have to be a post process
  22707. if (rigPostProcess) {
  22708. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22709. if (isPass) {
  22710. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22711. cam.isIntermediate = this._postProcesses.length === 0;
  22712. }
  22713. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22714. rigPostProcess.markTextureDirty();
  22715. }
  22716. else {
  22717. cam._postProcesses = this._postProcesses.slice(0);
  22718. }
  22719. }
  22720. };
  22721. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22722. if (insertAt === void 0) { insertAt = null; }
  22723. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22724. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22725. return 0;
  22726. }
  22727. if (insertAt == null || insertAt < 0) {
  22728. this._postProcesses.push(postProcess);
  22729. }
  22730. else if (this._postProcesses[insertAt] === null) {
  22731. this._postProcesses[insertAt] = postProcess;
  22732. }
  22733. else {
  22734. this._postProcesses.splice(insertAt, 0, postProcess);
  22735. }
  22736. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22737. return this._postProcesses.indexOf(postProcess);
  22738. };
  22739. Camera.prototype.detachPostProcess = function (postProcess) {
  22740. var idx = this._postProcesses.indexOf(postProcess);
  22741. if (idx !== -1) {
  22742. this._postProcesses[idx] = null;
  22743. }
  22744. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22745. };
  22746. Camera.prototype.getWorldMatrix = function () {
  22747. if (this._isSynchronizedViewMatrix()) {
  22748. return this._worldMatrix;
  22749. }
  22750. // Getting the the view matrix will also compute the world matrix.
  22751. this.getViewMatrix();
  22752. return this._worldMatrix;
  22753. };
  22754. Camera.prototype._getViewMatrix = function () {
  22755. return BABYLON.Matrix.Identity();
  22756. };
  22757. Camera.prototype.getViewMatrix = function (force) {
  22758. if (!force && this._isSynchronizedViewMatrix()) {
  22759. return this._computedViewMatrix;
  22760. }
  22761. this.updateCache();
  22762. this._computedViewMatrix = this._getViewMatrix();
  22763. this._currentRenderId = this.getScene().getRenderId();
  22764. this._childRenderId = this._currentRenderId;
  22765. this._refreshFrustumPlanes = true;
  22766. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22767. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22768. }
  22769. this.onViewMatrixChangedObservable.notifyObservers(this);
  22770. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22771. return this._computedViewMatrix;
  22772. };
  22773. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22774. this._doNotComputeProjectionMatrix = true;
  22775. if (projection !== undefined) {
  22776. this._projectionMatrix = projection;
  22777. }
  22778. };
  22779. ;
  22780. Camera.prototype.unfreezeProjectionMatrix = function () {
  22781. this._doNotComputeProjectionMatrix = false;
  22782. };
  22783. ;
  22784. Camera.prototype.getProjectionMatrix = function (force) {
  22785. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22786. return this._projectionMatrix;
  22787. }
  22788. // Cache
  22789. this._cache.mode = this.mode;
  22790. this._cache.minZ = this.minZ;
  22791. this._cache.maxZ = this.maxZ;
  22792. // Matrix
  22793. this._refreshFrustumPlanes = true;
  22794. var engine = this.getEngine();
  22795. var scene = this.getScene();
  22796. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22797. this._cache.fov = this.fov;
  22798. this._cache.fovMode = this.fovMode;
  22799. this._cache.aspectRatio = engine.getAspectRatio(this);
  22800. if (this.minZ <= 0) {
  22801. this.minZ = 0.1;
  22802. }
  22803. if (scene.useRightHandedSystem) {
  22804. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22805. }
  22806. else {
  22807. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22808. }
  22809. }
  22810. else {
  22811. var halfWidth = engine.getRenderWidth() / 2.0;
  22812. var halfHeight = engine.getRenderHeight() / 2.0;
  22813. if (scene.useRightHandedSystem) {
  22814. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22815. }
  22816. else {
  22817. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22818. }
  22819. this._cache.orthoLeft = this.orthoLeft;
  22820. this._cache.orthoRight = this.orthoRight;
  22821. this._cache.orthoBottom = this.orthoBottom;
  22822. this._cache.orthoTop = this.orthoTop;
  22823. this._cache.renderWidth = engine.getRenderWidth();
  22824. this._cache.renderHeight = engine.getRenderHeight();
  22825. }
  22826. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22827. return this._projectionMatrix;
  22828. };
  22829. Camera.prototype.getTranformationMatrix = function () {
  22830. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22831. return this._transformMatrix;
  22832. };
  22833. Camera.prototype.updateFrustumPlanes = function () {
  22834. if (!this._refreshFrustumPlanes) {
  22835. return;
  22836. }
  22837. this.getTranformationMatrix();
  22838. if (!this._frustumPlanes) {
  22839. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22840. }
  22841. else {
  22842. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22843. }
  22844. this._refreshFrustumPlanes = false;
  22845. };
  22846. Camera.prototype.isInFrustum = function (target) {
  22847. this.updateFrustumPlanes();
  22848. return target.isInFrustum(this._frustumPlanes);
  22849. };
  22850. Camera.prototype.isCompletelyInFrustum = function (target) {
  22851. this.updateFrustumPlanes();
  22852. return target.isCompletelyInFrustum(this._frustumPlanes);
  22853. };
  22854. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22855. if (length === void 0) { length = 100; }
  22856. if (!transform) {
  22857. transform = this.getWorldMatrix();
  22858. }
  22859. if (!origin) {
  22860. origin = this.position;
  22861. }
  22862. var forward = new BABYLON.Vector3(0, 0, 1);
  22863. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22864. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22865. return new BABYLON.Ray(origin, direction, length);
  22866. };
  22867. /**
  22868. * Releases resources associated with this node.
  22869. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22870. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22871. */
  22872. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22873. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22874. // Observables
  22875. this.onViewMatrixChangedObservable.clear();
  22876. this.onProjectionMatrixChangedObservable.clear();
  22877. this.onAfterCheckInputsObservable.clear();
  22878. this.onRestoreStateObservable.clear();
  22879. // Inputs
  22880. if (this.inputs) {
  22881. this.inputs.clear();
  22882. }
  22883. // Animations
  22884. this.getScene().stopAnimation(this);
  22885. // Remove from scene
  22886. this.getScene().removeCamera(this);
  22887. while (this._rigCameras.length > 0) {
  22888. var camera = this._rigCameras.pop();
  22889. if (camera) {
  22890. camera.dispose();
  22891. }
  22892. }
  22893. // Postprocesses
  22894. if (this._rigPostProcess) {
  22895. this._rigPostProcess.dispose(this);
  22896. this._rigPostProcess = null;
  22897. this._postProcesses = [];
  22898. }
  22899. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22900. this._rigPostProcess = null;
  22901. this._postProcesses = [];
  22902. }
  22903. else {
  22904. var i = this._postProcesses.length;
  22905. while (--i >= 0) {
  22906. var postProcess = this._postProcesses[i];
  22907. if (postProcess) {
  22908. postProcess.dispose(this);
  22909. }
  22910. }
  22911. }
  22912. // Render targets
  22913. var i = this.customRenderTargets.length;
  22914. while (--i >= 0) {
  22915. this.customRenderTargets[i].dispose();
  22916. }
  22917. this.customRenderTargets = [];
  22918. // Active Meshes
  22919. this._activeMeshes.dispose();
  22920. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22921. };
  22922. Object.defineProperty(Camera.prototype, "leftCamera", {
  22923. // ---- Camera rigs section ----
  22924. get: function () {
  22925. if (this._rigCameras.length < 1) {
  22926. return null;
  22927. }
  22928. return this._rigCameras[0];
  22929. },
  22930. enumerable: true,
  22931. configurable: true
  22932. });
  22933. Object.defineProperty(Camera.prototype, "rightCamera", {
  22934. get: function () {
  22935. if (this._rigCameras.length < 2) {
  22936. return null;
  22937. }
  22938. return this._rigCameras[1];
  22939. },
  22940. enumerable: true,
  22941. configurable: true
  22942. });
  22943. Camera.prototype.getLeftTarget = function () {
  22944. if (this._rigCameras.length < 1) {
  22945. return null;
  22946. }
  22947. return this._rigCameras[0].getTarget();
  22948. };
  22949. Camera.prototype.getRightTarget = function () {
  22950. if (this._rigCameras.length < 2) {
  22951. return null;
  22952. }
  22953. return this._rigCameras[1].getTarget();
  22954. };
  22955. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22956. if (this.cameraRigMode === mode) {
  22957. return;
  22958. }
  22959. while (this._rigCameras.length > 0) {
  22960. var camera = this._rigCameras.pop();
  22961. if (camera) {
  22962. camera.dispose();
  22963. }
  22964. }
  22965. this.cameraRigMode = mode;
  22966. this._cameraRigParams = {};
  22967. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22968. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22969. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22970. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22971. // create the rig cameras, unless none
  22972. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22973. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22974. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22975. if (leftCamera && rightCamera) {
  22976. this._rigCameras.push(leftCamera);
  22977. this._rigCameras.push(rightCamera);
  22978. }
  22979. }
  22980. switch (this.cameraRigMode) {
  22981. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22982. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22983. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22984. break;
  22985. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22986. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22987. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22988. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22989. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22990. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22991. break;
  22992. case Camera.RIG_MODE_VR:
  22993. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22994. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22995. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22996. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22997. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22998. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22999. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23000. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23001. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23002. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23003. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23004. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23005. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23006. if (metrics.compensateDistortion) {
  23007. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23008. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23009. }
  23010. break;
  23011. case Camera.RIG_MODE_WEBVR:
  23012. if (rigParams.vrDisplay) {
  23013. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23014. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23015. //Left eye
  23016. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23017. this._rigCameras[0].setCameraRigParameter("left", true);
  23018. //leaving this for future reference
  23019. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23020. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23021. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23022. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23023. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23024. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23025. this._rigCameras[0].parent = this;
  23026. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23027. //Right eye
  23028. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23029. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23030. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23031. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23032. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23033. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23034. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23035. this._rigCameras[1].parent = this;
  23036. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23037. if (Camera.UseAlternateWebVRRendering) {
  23038. this._rigCameras[1]._skipRendering = true;
  23039. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23040. }
  23041. }
  23042. break;
  23043. }
  23044. this._cascadePostProcessesToRigCams();
  23045. this.update();
  23046. };
  23047. Camera.prototype._getVRProjectionMatrix = function () {
  23048. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23049. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23050. return this._projectionMatrix;
  23051. };
  23052. Camera.prototype._updateCameraRotationMatrix = function () {
  23053. //Here for WebVR
  23054. };
  23055. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23056. //Here for WebVR
  23057. };
  23058. /**
  23059. * This function MUST be overwritten by the different WebVR cameras available.
  23060. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23061. */
  23062. Camera.prototype._getWebVRProjectionMatrix = function () {
  23063. return BABYLON.Matrix.Identity();
  23064. };
  23065. /**
  23066. * This function MUST be overwritten by the different WebVR cameras available.
  23067. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23068. */
  23069. Camera.prototype._getWebVRViewMatrix = function () {
  23070. return BABYLON.Matrix.Identity();
  23071. };
  23072. Camera.prototype.setCameraRigParameter = function (name, value) {
  23073. if (!this._cameraRigParams) {
  23074. this._cameraRigParams = {};
  23075. }
  23076. this._cameraRigParams[name] = value;
  23077. //provisionnally:
  23078. if (name === "interaxialDistance") {
  23079. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23080. }
  23081. };
  23082. /**
  23083. * needs to be overridden by children so sub has required properties to be copied
  23084. */
  23085. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23086. return null;
  23087. };
  23088. /**
  23089. * May need to be overridden by children
  23090. */
  23091. Camera.prototype._updateRigCameras = function () {
  23092. for (var i = 0; i < this._rigCameras.length; i++) {
  23093. this._rigCameras[i].minZ = this.minZ;
  23094. this._rigCameras[i].maxZ = this.maxZ;
  23095. this._rigCameras[i].fov = this.fov;
  23096. }
  23097. // only update viewport when ANAGLYPH
  23098. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23099. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23100. }
  23101. };
  23102. Camera.prototype._setupInputs = function () {
  23103. };
  23104. Camera.prototype.serialize = function () {
  23105. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23106. // Type
  23107. serializationObject.type = this.getClassName();
  23108. // Parent
  23109. if (this.parent) {
  23110. serializationObject.parentId = this.parent.id;
  23111. }
  23112. if (this.inputs) {
  23113. this.inputs.serialize(serializationObject);
  23114. }
  23115. // Animations
  23116. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23117. serializationObject.ranges = this.serializeAnimationRanges();
  23118. return serializationObject;
  23119. };
  23120. Camera.prototype.clone = function (name) {
  23121. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23122. };
  23123. Camera.prototype.getDirection = function (localAxis) {
  23124. var result = BABYLON.Vector3.Zero();
  23125. this.getDirectionToRef(localAxis, result);
  23126. return result;
  23127. };
  23128. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23129. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23130. };
  23131. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23132. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23133. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23134. switch (type) {
  23135. case "ArcRotateCamera":
  23136. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23137. case "DeviceOrientationCamera":
  23138. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23139. case "FollowCamera":
  23140. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23141. case "ArcFollowCamera":
  23142. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23143. case "GamepadCamera":
  23144. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23145. case "TouchCamera":
  23146. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23147. case "VirtualJoysticksCamera":
  23148. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23149. case "WebVRFreeCamera":
  23150. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23151. case "WebVRGamepadCamera":
  23152. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23153. case "VRDeviceOrientationFreeCamera":
  23154. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23155. case "VRDeviceOrientationGamepadCamera":
  23156. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23157. case "AnaglyphArcRotateCamera":
  23158. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23159. case "AnaglyphFreeCamera":
  23160. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23161. case "AnaglyphGamepadCamera":
  23162. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23163. case "AnaglyphUniversalCamera":
  23164. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23165. case "StereoscopicArcRotateCamera":
  23166. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23167. case "StereoscopicFreeCamera":
  23168. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23169. case "StereoscopicGamepadCamera":
  23170. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23171. case "StereoscopicUniversalCamera":
  23172. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23173. case "FreeCamera": // Forcing Universal here
  23174. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23175. default: // Universal Camera is the default value
  23176. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23177. }
  23178. };
  23179. Camera.prototype.computeWorldMatrix = function () {
  23180. return this.getWorldMatrix();
  23181. };
  23182. Camera.Parse = function (parsedCamera, scene) {
  23183. var type = parsedCamera.type;
  23184. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23185. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23186. // Parent
  23187. if (parsedCamera.parentId) {
  23188. camera._waitingParentId = parsedCamera.parentId;
  23189. }
  23190. //If camera has an input manager, let it parse inputs settings
  23191. if (camera.inputs) {
  23192. camera.inputs.parse(parsedCamera);
  23193. camera._setupInputs();
  23194. }
  23195. if (camera.setPosition) { // need to force position
  23196. camera.position.copyFromFloats(0, 0, 0);
  23197. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23198. }
  23199. // Target
  23200. if (parsedCamera.target) {
  23201. if (camera.setTarget) {
  23202. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23203. }
  23204. }
  23205. // Apply 3d rig, when found
  23206. if (parsedCamera.cameraRigMode) {
  23207. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23208. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23209. }
  23210. // Animations
  23211. if (parsedCamera.animations) {
  23212. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23213. var parsedAnimation = parsedCamera.animations[animationIndex];
  23214. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23215. }
  23216. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23217. }
  23218. if (parsedCamera.autoAnimate) {
  23219. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23220. }
  23221. return camera;
  23222. };
  23223. // Statics
  23224. Camera._PERSPECTIVE_CAMERA = 0;
  23225. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23226. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23227. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23228. Camera._RIG_MODE_NONE = 0;
  23229. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23230. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23231. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23232. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23233. Camera._RIG_MODE_VR = 20;
  23234. Camera._RIG_MODE_WEBVR = 21;
  23235. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23236. Camera.UseAlternateWebVRRendering = false;
  23237. __decorate([
  23238. BABYLON.serializeAsVector3()
  23239. ], Camera.prototype, "position", void 0);
  23240. __decorate([
  23241. BABYLON.serializeAsVector3()
  23242. ], Camera.prototype, "upVector", void 0);
  23243. __decorate([
  23244. BABYLON.serialize()
  23245. ], Camera.prototype, "orthoLeft", void 0);
  23246. __decorate([
  23247. BABYLON.serialize()
  23248. ], Camera.prototype, "orthoRight", void 0);
  23249. __decorate([
  23250. BABYLON.serialize()
  23251. ], Camera.prototype, "orthoBottom", void 0);
  23252. __decorate([
  23253. BABYLON.serialize()
  23254. ], Camera.prototype, "orthoTop", void 0);
  23255. __decorate([
  23256. BABYLON.serialize()
  23257. ], Camera.prototype, "fov", void 0);
  23258. __decorate([
  23259. BABYLON.serialize()
  23260. ], Camera.prototype, "minZ", void 0);
  23261. __decorate([
  23262. BABYLON.serialize()
  23263. ], Camera.prototype, "maxZ", void 0);
  23264. __decorate([
  23265. BABYLON.serialize()
  23266. ], Camera.prototype, "inertia", void 0);
  23267. __decorate([
  23268. BABYLON.serialize()
  23269. ], Camera.prototype, "mode", void 0);
  23270. __decorate([
  23271. BABYLON.serialize()
  23272. ], Camera.prototype, "layerMask", void 0);
  23273. __decorate([
  23274. BABYLON.serialize()
  23275. ], Camera.prototype, "fovMode", void 0);
  23276. __decorate([
  23277. BABYLON.serialize()
  23278. ], Camera.prototype, "cameraRigMode", void 0);
  23279. __decorate([
  23280. BABYLON.serialize()
  23281. ], Camera.prototype, "interaxialDistance", void 0);
  23282. __decorate([
  23283. BABYLON.serialize()
  23284. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23285. return Camera;
  23286. }(BABYLON.Node));
  23287. BABYLON.Camera = Camera;
  23288. })(BABYLON || (BABYLON = {}));
  23289. //# sourceMappingURL=babylon.camera.js.map
  23290. var BABYLON;
  23291. (function (BABYLON) {
  23292. var RenderingManager = /** @class */ (function () {
  23293. function RenderingManager(scene) {
  23294. this._renderingGroups = new Array();
  23295. this._autoClearDepthStencil = {};
  23296. this._customOpaqueSortCompareFn = {};
  23297. this._customAlphaTestSortCompareFn = {};
  23298. this._customTransparentSortCompareFn = {};
  23299. this._renderinGroupInfo = null;
  23300. this._scene = scene;
  23301. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23302. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23303. }
  23304. }
  23305. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23306. if (depth === void 0) { depth = true; }
  23307. if (stencil === void 0) { stencil = true; }
  23308. if (this._depthStencilBufferAlreadyCleaned) {
  23309. return;
  23310. }
  23311. this._scene.getEngine().clear(null, false, depth, stencil);
  23312. this._depthStencilBufferAlreadyCleaned = true;
  23313. };
  23314. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23315. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23316. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23317. var info = null;
  23318. if (observable) {
  23319. if (!this._renderinGroupInfo) {
  23320. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23321. }
  23322. info = this._renderinGroupInfo;
  23323. info.scene = this._scene;
  23324. info.camera = this._scene.activeCamera;
  23325. }
  23326. // Dispatch sprites
  23327. if (renderSprites) {
  23328. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23329. var manager = this._scene.spriteManagers[index];
  23330. this.dispatchSprites(manager);
  23331. }
  23332. }
  23333. // Render
  23334. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23335. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23336. var renderingGroup = this._renderingGroups[index];
  23337. if (!renderingGroup && !observable)
  23338. continue;
  23339. var renderingGroupMask = 0;
  23340. // Fire PRECLEAR stage
  23341. if (observable && info) {
  23342. renderingGroupMask = Math.pow(2, index);
  23343. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23344. info.renderingGroupId = index;
  23345. observable.notifyObservers(info, renderingGroupMask);
  23346. }
  23347. // Clear depth/stencil if needed
  23348. if (RenderingManager.AUTOCLEAR) {
  23349. var autoClear = this._autoClearDepthStencil[index];
  23350. if (autoClear && autoClear.autoClear) {
  23351. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23352. }
  23353. }
  23354. if (observable && info) {
  23355. // Fire PREOPAQUE stage
  23356. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23357. observable.notifyObservers(info, renderingGroupMask);
  23358. // Fire PRETRANSPARENT stage
  23359. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23360. observable.notifyObservers(info, renderingGroupMask);
  23361. }
  23362. if (renderingGroup) {
  23363. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23364. var step = _a[_i];
  23365. step.action(index);
  23366. }
  23367. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23368. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23369. var step = _c[_b];
  23370. step.action(index);
  23371. }
  23372. }
  23373. // Fire POSTTRANSPARENT stage
  23374. if (observable && info) {
  23375. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23376. observable.notifyObservers(info, renderingGroupMask);
  23377. }
  23378. }
  23379. };
  23380. RenderingManager.prototype.reset = function () {
  23381. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23382. var renderingGroup = this._renderingGroups[index];
  23383. if (renderingGroup) {
  23384. renderingGroup.prepare();
  23385. }
  23386. }
  23387. };
  23388. RenderingManager.prototype.dispose = function () {
  23389. this.freeRenderingGroups();
  23390. this._renderingGroups.length = 0;
  23391. };
  23392. /**
  23393. * Clear the info related to rendering groups preventing retention points during dispose.
  23394. */
  23395. RenderingManager.prototype.freeRenderingGroups = function () {
  23396. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23397. var renderingGroup = this._renderingGroups[index];
  23398. if (renderingGroup) {
  23399. renderingGroup.dispose();
  23400. }
  23401. }
  23402. };
  23403. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23404. if (this._renderingGroups[renderingGroupId] === undefined) {
  23405. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23406. }
  23407. };
  23408. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23409. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23410. this._prepareRenderingGroup(renderingGroupId);
  23411. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23412. };
  23413. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23414. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23415. this._prepareRenderingGroup(renderingGroupId);
  23416. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23417. };
  23418. /**
  23419. * @param subMesh The submesh to dispatch
  23420. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23421. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23422. */
  23423. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23424. if (mesh === undefined) {
  23425. mesh = subMesh.getMesh();
  23426. }
  23427. var renderingGroupId = mesh.renderingGroupId || 0;
  23428. this._prepareRenderingGroup(renderingGroupId);
  23429. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23430. };
  23431. /**
  23432. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23433. * This allowed control for front to back rendering or reversly depending of the special needs.
  23434. *
  23435. * @param renderingGroupId The rendering group id corresponding to its index
  23436. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23437. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23438. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23439. */
  23440. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23441. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23442. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23443. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23444. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23445. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23446. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23447. if (this._renderingGroups[renderingGroupId]) {
  23448. var group = this._renderingGroups[renderingGroupId];
  23449. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23450. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23451. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23452. }
  23453. };
  23454. /**
  23455. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23456. *
  23457. * @param renderingGroupId The rendering group id corresponding to its index
  23458. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23459. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23460. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23461. */
  23462. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23463. if (depth === void 0) { depth = true; }
  23464. if (stencil === void 0) { stencil = true; }
  23465. this._autoClearDepthStencil[renderingGroupId] = {
  23466. autoClear: autoClearDepthStencil,
  23467. depth: depth,
  23468. stencil: stencil
  23469. };
  23470. };
  23471. /**
  23472. * The max id used for rendering groups (not included)
  23473. */
  23474. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23475. /**
  23476. * The min id used for rendering groups (included)
  23477. */
  23478. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23479. /**
  23480. * Used to globally prevent autoclearing scenes.
  23481. */
  23482. RenderingManager.AUTOCLEAR = true;
  23483. return RenderingManager;
  23484. }());
  23485. BABYLON.RenderingManager = RenderingManager;
  23486. })(BABYLON || (BABYLON = {}));
  23487. //# sourceMappingURL=babylon.renderingManager.js.map
  23488. var BABYLON;
  23489. (function (BABYLON) {
  23490. var RenderingGroup = /** @class */ (function () {
  23491. /**
  23492. * Creates a new rendering group.
  23493. * @param index The rendering group index
  23494. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23495. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23496. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23497. */
  23498. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23499. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23500. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23501. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23502. this.index = index;
  23503. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23504. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23505. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23506. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23507. this._particleSystems = new BABYLON.SmartArray(256);
  23508. this._spriteManagers = new BABYLON.SmartArray(256);
  23509. this._edgesRenderers = new BABYLON.SmartArray(16);
  23510. this._scene = scene;
  23511. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23512. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23513. this.transparentSortCompareFn = transparentSortCompareFn;
  23514. }
  23515. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23516. /**
  23517. * Set the opaque sort comparison function.
  23518. * If null the sub meshes will be render in the order they were created
  23519. */
  23520. set: function (value) {
  23521. this._opaqueSortCompareFn = value;
  23522. if (value) {
  23523. this._renderOpaque = this.renderOpaqueSorted;
  23524. }
  23525. else {
  23526. this._renderOpaque = RenderingGroup.renderUnsorted;
  23527. }
  23528. },
  23529. enumerable: true,
  23530. configurable: true
  23531. });
  23532. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23533. /**
  23534. * Set the alpha test sort comparison function.
  23535. * If null the sub meshes will be render in the order they were created
  23536. */
  23537. set: function (value) {
  23538. this._alphaTestSortCompareFn = value;
  23539. if (value) {
  23540. this._renderAlphaTest = this.renderAlphaTestSorted;
  23541. }
  23542. else {
  23543. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23544. }
  23545. },
  23546. enumerable: true,
  23547. configurable: true
  23548. });
  23549. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23550. /**
  23551. * Set the transparent sort comparison function.
  23552. * If null the sub meshes will be render in the order they were created
  23553. */
  23554. set: function (value) {
  23555. if (value) {
  23556. this._transparentSortCompareFn = value;
  23557. }
  23558. else {
  23559. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23560. }
  23561. this._renderTransparent = this.renderTransparentSorted;
  23562. },
  23563. enumerable: true,
  23564. configurable: true
  23565. });
  23566. /**
  23567. * Render all the sub meshes contained in the group.
  23568. * @param customRenderFunction Used to override the default render behaviour of the group.
  23569. * @returns true if rendered some submeshes.
  23570. */
  23571. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23572. if (customRenderFunction) {
  23573. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23574. return;
  23575. }
  23576. var engine = this._scene.getEngine();
  23577. // Depth only
  23578. if (this._depthOnlySubMeshes.length !== 0) {
  23579. engine.setColorWrite(false);
  23580. this._renderAlphaTest(this._depthOnlySubMeshes);
  23581. engine.setColorWrite(true);
  23582. }
  23583. // Opaque
  23584. if (this._opaqueSubMeshes.length !== 0) {
  23585. this._renderOpaque(this._opaqueSubMeshes);
  23586. }
  23587. // Alpha test
  23588. if (this._alphaTestSubMeshes.length !== 0) {
  23589. this._renderAlphaTest(this._alphaTestSubMeshes);
  23590. }
  23591. var stencilState = engine.getStencilBuffer();
  23592. engine.setStencilBuffer(false);
  23593. // Sprites
  23594. if (renderSprites) {
  23595. this._renderSprites();
  23596. }
  23597. // Particles
  23598. if (renderParticles) {
  23599. this._renderParticles(activeMeshes);
  23600. }
  23601. if (this.onBeforeTransparentRendering) {
  23602. this.onBeforeTransparentRendering();
  23603. }
  23604. // Transparent
  23605. if (this._transparentSubMeshes.length !== 0) {
  23606. this._renderTransparent(this._transparentSubMeshes);
  23607. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23608. }
  23609. // Set back stencil to false in case it changes before the edge renderer.
  23610. engine.setStencilBuffer(false);
  23611. // Edges
  23612. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23613. this._edgesRenderers.data[edgesRendererIndex].render();
  23614. }
  23615. // Restore Stencil state.
  23616. engine.setStencilBuffer(stencilState);
  23617. };
  23618. /**
  23619. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23620. * @param subMeshes The submeshes to render
  23621. */
  23622. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23623. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23624. };
  23625. /**
  23626. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23627. * @param subMeshes The submeshes to render
  23628. */
  23629. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23630. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23631. };
  23632. /**
  23633. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23634. * @param subMeshes The submeshes to render
  23635. */
  23636. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23637. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23638. };
  23639. /**
  23640. * Renders the submeshes in a specified order.
  23641. * @param subMeshes The submeshes to sort before render
  23642. * @param sortCompareFn The comparison function use to sort
  23643. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23644. * @param transparent Specifies to activate blending if true
  23645. */
  23646. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23647. var subIndex = 0;
  23648. var subMesh;
  23649. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23650. for (; subIndex < subMeshes.length; subIndex++) {
  23651. subMesh = subMeshes.data[subIndex];
  23652. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23653. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23654. }
  23655. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23656. if (sortCompareFn) {
  23657. sortedArray.sort(sortCompareFn);
  23658. }
  23659. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23660. subMesh = sortedArray[subIndex];
  23661. if (transparent) {
  23662. var material = subMesh.getMaterial();
  23663. if (material && material.needDepthPrePass) {
  23664. var engine = material.getScene().getEngine();
  23665. engine.setColorWrite(false);
  23666. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23667. subMesh.render(false);
  23668. engine.setColorWrite(true);
  23669. }
  23670. }
  23671. subMesh.render(transparent);
  23672. }
  23673. };
  23674. /**
  23675. * Renders the submeshes in the order they were dispatched (no sort applied).
  23676. * @param subMeshes The submeshes to render
  23677. */
  23678. RenderingGroup.renderUnsorted = function (subMeshes) {
  23679. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23680. var submesh = subMeshes.data[subIndex];
  23681. submesh.render(false);
  23682. }
  23683. };
  23684. /**
  23685. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23686. * are rendered back to front if in the same alpha index.
  23687. *
  23688. * @param a The first submesh
  23689. * @param b The second submesh
  23690. * @returns The result of the comparison
  23691. */
  23692. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23693. // Alpha index first
  23694. if (a._alphaIndex > b._alphaIndex) {
  23695. return 1;
  23696. }
  23697. if (a._alphaIndex < b._alphaIndex) {
  23698. return -1;
  23699. }
  23700. // Then distance to camera
  23701. return RenderingGroup.backToFrontSortCompare(a, b);
  23702. };
  23703. /**
  23704. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23705. * are rendered back to front.
  23706. *
  23707. * @param a The first submesh
  23708. * @param b The second submesh
  23709. * @returns The result of the comparison
  23710. */
  23711. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23712. // Then distance to camera
  23713. if (a._distanceToCamera < b._distanceToCamera) {
  23714. return 1;
  23715. }
  23716. if (a._distanceToCamera > b._distanceToCamera) {
  23717. return -1;
  23718. }
  23719. return 0;
  23720. };
  23721. /**
  23722. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23723. * are rendered front to back (prevent overdraw).
  23724. *
  23725. * @param a The first submesh
  23726. * @param b The second submesh
  23727. * @returns The result of the comparison
  23728. */
  23729. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23730. // Then distance to camera
  23731. if (a._distanceToCamera < b._distanceToCamera) {
  23732. return -1;
  23733. }
  23734. if (a._distanceToCamera > b._distanceToCamera) {
  23735. return 1;
  23736. }
  23737. return 0;
  23738. };
  23739. /**
  23740. * Resets the different lists of submeshes to prepare a new frame.
  23741. */
  23742. RenderingGroup.prototype.prepare = function () {
  23743. this._opaqueSubMeshes.reset();
  23744. this._transparentSubMeshes.reset();
  23745. this._alphaTestSubMeshes.reset();
  23746. this._depthOnlySubMeshes.reset();
  23747. this._particleSystems.reset();
  23748. this._spriteManagers.reset();
  23749. this._edgesRenderers.reset();
  23750. };
  23751. RenderingGroup.prototype.dispose = function () {
  23752. this._opaqueSubMeshes.dispose();
  23753. this._transparentSubMeshes.dispose();
  23754. this._alphaTestSubMeshes.dispose();
  23755. this._depthOnlySubMeshes.dispose();
  23756. this._particleSystems.dispose();
  23757. this._spriteManagers.dispose();
  23758. this._edgesRenderers.dispose();
  23759. };
  23760. /**
  23761. * Inserts the submesh in its correct queue depending on its material.
  23762. * @param subMesh The submesh to dispatch
  23763. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23764. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23765. */
  23766. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23767. // Get mesh and materials if not provided
  23768. if (mesh === undefined) {
  23769. mesh = subMesh.getMesh();
  23770. }
  23771. if (material === undefined) {
  23772. material = subMesh.getMaterial();
  23773. }
  23774. if (material === null || material === undefined) {
  23775. return;
  23776. }
  23777. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23778. this._transparentSubMeshes.push(subMesh);
  23779. }
  23780. else if (material.needAlphaTesting()) { // Alpha test
  23781. if (material.needDepthPrePass) {
  23782. this._depthOnlySubMeshes.push(subMesh);
  23783. }
  23784. this._alphaTestSubMeshes.push(subMesh);
  23785. }
  23786. else {
  23787. if (material.needDepthPrePass) {
  23788. this._depthOnlySubMeshes.push(subMesh);
  23789. }
  23790. this._opaqueSubMeshes.push(subMesh); // Opaque
  23791. }
  23792. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23793. this._edgesRenderers.push(mesh._edgesRenderer);
  23794. }
  23795. };
  23796. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23797. this._spriteManagers.push(spriteManager);
  23798. };
  23799. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23800. this._particleSystems.push(particleSystem);
  23801. };
  23802. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23803. if (this._particleSystems.length === 0) {
  23804. return;
  23805. }
  23806. // Particles
  23807. var activeCamera = this._scene.activeCamera;
  23808. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23809. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23810. var particleSystem = this._particleSystems.data[particleIndex];
  23811. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23812. continue;
  23813. }
  23814. var emitter = particleSystem.emitter;
  23815. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23816. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23817. }
  23818. }
  23819. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23820. };
  23821. RenderingGroup.prototype._renderSprites = function () {
  23822. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23823. return;
  23824. }
  23825. // Sprites
  23826. var activeCamera = this._scene.activeCamera;
  23827. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23828. for (var id = 0; id < this._spriteManagers.length; id++) {
  23829. var spriteManager = this._spriteManagers.data[id];
  23830. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23831. spriteManager.render();
  23832. }
  23833. }
  23834. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23835. };
  23836. return RenderingGroup;
  23837. }());
  23838. BABYLON.RenderingGroup = RenderingGroup;
  23839. })(BABYLON || (BABYLON = {}));
  23840. //# sourceMappingURL=babylon.renderingGroup.js.map
  23841. var BABYLON;
  23842. (function (BABYLON) {
  23843. /**
  23844. * Groups all the scene component constants in one place to ease maintenance.
  23845. * @hidden
  23846. */
  23847. var SceneComponentConstants = /** @class */ (function () {
  23848. function SceneComponentConstants() {
  23849. }
  23850. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23851. SceneComponentConstants.NAME_LAYER = "Layer";
  23852. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23853. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23854. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23855. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23856. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23857. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23858. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23859. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23860. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23861. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23862. return SceneComponentConstants;
  23863. }());
  23864. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23865. /**
  23866. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23867. * @hidden
  23868. */
  23869. var Stage = /** @class */ (function (_super) {
  23870. __extends(Stage, _super);
  23871. /**
  23872. * Hide ctor from the rest of the world.
  23873. * @param items The items to add.
  23874. */
  23875. function Stage(items) {
  23876. return _super.apply(this, items) || this;
  23877. }
  23878. /**
  23879. * Creates a new Stage.
  23880. * @returns A new instance of a Stage
  23881. */
  23882. Stage.Create = function () {
  23883. return Object.create(Stage.prototype);
  23884. };
  23885. /**
  23886. * Registers a step in an ordered way in the targeted stage.
  23887. * @param index Defines the position to register the step in
  23888. * @param component Defines the component attached to the step
  23889. * @param action Defines the action to launch during the step
  23890. */
  23891. Stage.prototype.registerStep = function (index, component, action) {
  23892. var i = 0;
  23893. var maxIndex = Number.MAX_VALUE;
  23894. for (; i < this.length && i < maxIndex; i++) {
  23895. var step = this[i];
  23896. maxIndex = step.index;
  23897. }
  23898. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23899. };
  23900. /**
  23901. * Clears all the steps from the stage.
  23902. */
  23903. Stage.prototype.clear = function () {
  23904. this.length = 0;
  23905. };
  23906. return Stage;
  23907. }(Array));
  23908. BABYLON.Stage = Stage;
  23909. })(BABYLON || (BABYLON = {}));
  23910. //# sourceMappingURL=babylon.sceneComponent.js.map
  23911. var BABYLON;
  23912. (function (BABYLON) {
  23913. /**
  23914. * Base class of the scene acting as a container for the different elements composing a scene.
  23915. * This class is dynamically extended by the different components of the scene increasing
  23916. * flexibility and reducing coupling.
  23917. */
  23918. var AbstractScene = /** @class */ (function () {
  23919. function AbstractScene() {
  23920. /** All of the cameras added to this scene
  23921. * @see http://doc.babylonjs.com/babylon101/cameras
  23922. */
  23923. this.cameras = new Array();
  23924. /**
  23925. * All of the lights added to this scene
  23926. * @see http://doc.babylonjs.com/babylon101/lights
  23927. */
  23928. this.lights = new Array();
  23929. /**
  23930. * All of the (abstract) meshes added to this scene
  23931. */
  23932. this.meshes = new Array();
  23933. /**
  23934. * The list of skeletons added to the scene
  23935. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23936. */
  23937. this.skeletons = new Array();
  23938. /**
  23939. * All of the particle systems added to this scene
  23940. * @see http://doc.babylonjs.com/babylon101/particles
  23941. */
  23942. this.particleSystems = new Array();
  23943. /**
  23944. * Gets a list of Animations associated with the scene
  23945. */
  23946. this.animations = [];
  23947. /**
  23948. * All of the animation groups added to this scene
  23949. * @see http://doc.babylonjs.com/how_to/group
  23950. */
  23951. this.animationGroups = new Array();
  23952. /**
  23953. * All of the multi-materials added to this scene
  23954. * @see http://doc.babylonjs.com/how_to/multi_materials
  23955. */
  23956. this.multiMaterials = new Array();
  23957. /**
  23958. * All of the materials added to this scene
  23959. * @see http://doc.babylonjs.com/babylon101/materials
  23960. */
  23961. this.materials = new Array();
  23962. /**
  23963. * The list of morph target managers added to the scene
  23964. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23965. */
  23966. this.morphTargetManagers = new Array();
  23967. /**
  23968. * The list of geometries used in the scene.
  23969. */
  23970. this.geometries = new Array();
  23971. /**
  23972. * All of the tranform nodes added to this scene
  23973. * @see http://doc.babylonjs.com/how_to/transformnode
  23974. */
  23975. this.transformNodes = new Array();
  23976. /**
  23977. * ActionManagers available on the scene.
  23978. */
  23979. this.actionManagers = new Array();
  23980. /**
  23981. * Sounds to keep.
  23982. */
  23983. this.sounds = new Array();
  23984. /**
  23985. * Textures to keep.
  23986. */
  23987. this.textures = new Array();
  23988. }
  23989. /**
  23990. * Adds a parser in the list of availables ones.
  23991. * @param name Defines the name of the parser
  23992. * @param parser Defines the parser to add
  23993. */
  23994. AbstractScene.AddParser = function (name, parser) {
  23995. this._BabylonFileParsers[name] = parser;
  23996. };
  23997. /**
  23998. * Parser json data and populate both a scene and its associated container object
  23999. * @param jsonData Defines the data to parse
  24000. * @param scene Defines the scene to parse the data for
  24001. * @param container Defines the container attached to the parsing sequence
  24002. * @param rootUrl Defines the root url of the data
  24003. */
  24004. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24005. for (var parserName in this._BabylonFileParsers) {
  24006. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24007. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24008. }
  24009. }
  24010. };
  24011. /**
  24012. * Stores the list of available parsers in the application.
  24013. */
  24014. AbstractScene._BabylonFileParsers = {};
  24015. return AbstractScene;
  24016. }());
  24017. BABYLON.AbstractScene = AbstractScene;
  24018. })(BABYLON || (BABYLON = {}));
  24019. //# sourceMappingURL=babylon.abstractScene.js.map
  24020. var BABYLON;
  24021. (function (BABYLON) {
  24022. /** @hidden */
  24023. var ClickInfo = /** @class */ (function () {
  24024. function ClickInfo() {
  24025. this._singleClick = false;
  24026. this._doubleClick = false;
  24027. this._hasSwiped = false;
  24028. this._ignore = false;
  24029. }
  24030. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24031. get: function () {
  24032. return this._singleClick;
  24033. },
  24034. set: function (b) {
  24035. this._singleClick = b;
  24036. },
  24037. enumerable: true,
  24038. configurable: true
  24039. });
  24040. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24041. get: function () {
  24042. return this._doubleClick;
  24043. },
  24044. set: function (b) {
  24045. this._doubleClick = b;
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24051. get: function () {
  24052. return this._hasSwiped;
  24053. },
  24054. set: function (b) {
  24055. this._hasSwiped = b;
  24056. },
  24057. enumerable: true,
  24058. configurable: true
  24059. });
  24060. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24061. get: function () {
  24062. return this._ignore;
  24063. },
  24064. set: function (b) {
  24065. this._ignore = b;
  24066. },
  24067. enumerable: true,
  24068. configurable: true
  24069. });
  24070. return ClickInfo;
  24071. }());
  24072. /**
  24073. * This class is used by the onRenderingGroupObservable
  24074. */
  24075. var RenderingGroupInfo = /** @class */ (function () {
  24076. function RenderingGroupInfo() {
  24077. }
  24078. /**
  24079. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  24080. * This stage will be fired no matter what
  24081. */
  24082. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  24083. /**
  24084. * Called before opaque object are rendered.
  24085. * This stage will be fired only if there's 3D Opaque content to render
  24086. */
  24087. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  24088. /**
  24089. * Called after the opaque objects are rendered and before the transparent ones
  24090. * This stage will be fired only if there's 3D transparent content to render
  24091. */
  24092. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  24093. /**
  24094. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  24095. * This stage will be fired no matter what
  24096. */
  24097. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  24098. return RenderingGroupInfo;
  24099. }());
  24100. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24101. /**
  24102. * Represents a scene to be rendered by the engine.
  24103. * @see http://doc.babylonjs.com/features/scene
  24104. */
  24105. var Scene = /** @class */ (function (_super) {
  24106. __extends(Scene, _super);
  24107. /**
  24108. * Creates a new Scene
  24109. * @param engine defines the engine to use to render this scene
  24110. */
  24111. function Scene(engine) {
  24112. var _this = _super.call(this) || this;
  24113. // Members
  24114. /**
  24115. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24116. */
  24117. _this.autoClear = true;
  24118. /**
  24119. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24120. */
  24121. _this.autoClearDepthAndStencil = true;
  24122. /**
  24123. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24124. */
  24125. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24126. /**
  24127. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24128. */
  24129. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24130. _this._forceWireframe = false;
  24131. _this._forcePointsCloud = false;
  24132. /**
  24133. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  24134. */
  24135. _this.forceShowBoundingBoxes = false;
  24136. /**
  24137. * Gets or sets a boolean indicating if animations are enabled
  24138. */
  24139. _this.animationsEnabled = true;
  24140. _this._animationPropertiesOverride = null;
  24141. /**
  24142. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24143. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24144. */
  24145. _this.useConstantAnimationDeltaTime = false;
  24146. /**
  24147. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24148. * Please note that it requires to run a ray cast through the scene on every frame
  24149. */
  24150. _this.constantlyUpdateMeshUnderPointer = false;
  24151. /**
  24152. * Defines the HTML cursor to use when hovering over interactive elements
  24153. */
  24154. _this.hoverCursor = "pointer";
  24155. /**
  24156. * Defines the HTML default cursor to use (empty by default)
  24157. */
  24158. _this.defaultCursor = "";
  24159. /**
  24160. * This is used to call preventDefault() on pointer down
  24161. * in order to block unwanted artifacts like system double clicks
  24162. */
  24163. _this.preventDefaultOnPointerDown = true;
  24164. // Metadata
  24165. /**
  24166. * Gets or sets user defined metadata
  24167. */
  24168. _this.metadata = null;
  24169. /**
  24170. * Use this array to add regular expressions used to disable offline support for specific urls
  24171. */
  24172. _this.disableOfflineSupportExceptionRules = new Array();
  24173. /**
  24174. * An event triggered when the scene is disposed.
  24175. */
  24176. _this.onDisposeObservable = new BABYLON.Observable();
  24177. _this._onDisposeObserver = null;
  24178. /**
  24179. * An event triggered before rendering the scene (right after animations and physics)
  24180. */
  24181. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24182. _this._onBeforeRenderObserver = null;
  24183. /**
  24184. * An event triggered after rendering the scene
  24185. */
  24186. _this.onAfterRenderObservable = new BABYLON.Observable();
  24187. _this._onAfterRenderObserver = null;
  24188. /**
  24189. * An event triggered before animating the scene
  24190. */
  24191. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24192. /**
  24193. * An event triggered after animations processing
  24194. */
  24195. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24196. /**
  24197. * An event triggered before draw calls are ready to be sent
  24198. */
  24199. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24200. /**
  24201. * An event triggered after draw calls have been sent
  24202. */
  24203. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24204. /**
  24205. * An event triggered when physic simulation is about to be run
  24206. */
  24207. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24208. /**
  24209. * An event triggered when physic simulation has been done
  24210. */
  24211. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24212. /**
  24213. * An event triggered when the scene is ready
  24214. */
  24215. _this.onReadyObservable = new BABYLON.Observable();
  24216. /**
  24217. * An event triggered before rendering a camera
  24218. */
  24219. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24220. _this._onBeforeCameraRenderObserver = null;
  24221. /**
  24222. * An event triggered after rendering a camera
  24223. */
  24224. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24225. _this._onAfterCameraRenderObserver = null;
  24226. /**
  24227. * An event triggered when active meshes evaluation is about to start
  24228. */
  24229. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24230. /**
  24231. * An event triggered when active meshes evaluation is done
  24232. */
  24233. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24234. /**
  24235. * An event triggered when particles rendering is about to start
  24236. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24237. */
  24238. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24239. /**
  24240. * An event triggered when particles rendering is done
  24241. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24242. */
  24243. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24244. /**
  24245. * An event triggered when sprites rendering is about to start
  24246. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24247. */
  24248. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24249. /**
  24250. * An event triggered when sprites rendering is done
  24251. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24252. */
  24253. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24254. /**
  24255. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24256. */
  24257. _this.onDataLoadedObservable = new BABYLON.Observable();
  24258. /**
  24259. * An event triggered when a camera is created
  24260. */
  24261. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24262. /**
  24263. * An event triggered when a camera is removed
  24264. */
  24265. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24266. /**
  24267. * An event triggered when a light is created
  24268. */
  24269. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24270. /**
  24271. * An event triggered when a light is removed
  24272. */
  24273. _this.onLightRemovedObservable = new BABYLON.Observable();
  24274. /**
  24275. * An event triggered when a geometry is created
  24276. */
  24277. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24278. /**
  24279. * An event triggered when a geometry is removed
  24280. */
  24281. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24282. /**
  24283. * An event triggered when a transform node is created
  24284. */
  24285. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24286. /**
  24287. * An event triggered when a transform node is removed
  24288. */
  24289. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24290. /**
  24291. * An event triggered when a mesh is created
  24292. */
  24293. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24294. /**
  24295. * An event triggered when a mesh is removed
  24296. */
  24297. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24298. /**
  24299. * An event triggered when render targets are about to be rendered
  24300. * Can happen multiple times per frame.
  24301. */
  24302. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24303. /**
  24304. * An event triggered when render targets were rendered.
  24305. * Can happen multiple times per frame.
  24306. */
  24307. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24308. /**
  24309. * An event triggered before calculating deterministic simulation step
  24310. */
  24311. _this.onBeforeStepObservable = new BABYLON.Observable();
  24312. /**
  24313. * An event triggered after calculating deterministic simulation step
  24314. */
  24315. _this.onAfterStepObservable = new BABYLON.Observable();
  24316. /**
  24317. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24318. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24319. * 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)
  24320. */
  24321. _this.onRenderingGroupObservable = new BABYLON.Observable();
  24322. // Animations
  24323. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24324. /**
  24325. * 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).
  24326. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24327. */
  24328. _this.onPrePointerObservable = new BABYLON.Observable();
  24329. /**
  24330. * Observable event triggered each time an input event is received from the rendering canvas
  24331. */
  24332. _this.onPointerObservable = new BABYLON.Observable();
  24333. _this._meshPickProceed = false;
  24334. _this._currentPickResult = null;
  24335. _this._previousPickResult = null;
  24336. _this._totalPointersPressed = 0;
  24337. _this._doubleClickOccured = false;
  24338. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24339. _this.cameraToUseForPointers = null;
  24340. _this._pointerX = 0;
  24341. _this._pointerY = 0;
  24342. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24343. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24344. _this._startingPointerTime = 0;
  24345. _this._previousStartingPointerTime = 0;
  24346. _this._pointerCaptures = {};
  24347. // Deterministic lockstep
  24348. _this._timeAccumulator = 0;
  24349. _this._currentStepId = 0;
  24350. _this._currentInternalStep = 0;
  24351. // Keyboard
  24352. /**
  24353. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24354. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24355. */
  24356. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24357. /**
  24358. * Observable event triggered each time an keyboard event is received from the hosting window
  24359. */
  24360. _this.onKeyboardObservable = new BABYLON.Observable();
  24361. // Coordinates system
  24362. _this._useRightHandedSystem = false;
  24363. // Fog
  24364. _this._fogEnabled = true;
  24365. _this._fogMode = Scene.FOGMODE_NONE;
  24366. /**
  24367. * Gets or sets the fog color to use
  24368. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24369. */
  24370. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24371. /**
  24372. * Gets or sets the fog density to use
  24373. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24374. */
  24375. _this.fogDensity = 0.1;
  24376. /**
  24377. * Gets or sets the fog start distance to use
  24378. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24379. */
  24380. _this.fogStart = 0;
  24381. /**
  24382. * Gets or sets the fog end distance to use
  24383. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24384. */
  24385. _this.fogEnd = 1000.0;
  24386. // Lights
  24387. _this._shadowsEnabled = true;
  24388. _this._lightsEnabled = true;
  24389. /** All of the active cameras added to this scene. */
  24390. _this.activeCameras = new Array();
  24391. // Textures
  24392. _this._texturesEnabled = true;
  24393. // Particles
  24394. /**
  24395. * Gets or sets a boolean indicating if particles are enabled on this scene
  24396. */
  24397. _this.particlesEnabled = true;
  24398. // Sprites
  24399. /**
  24400. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24401. */
  24402. _this.spritesEnabled = true;
  24403. /**
  24404. * All of the sprite managers added to this scene
  24405. * @see http://doc.babylonjs.com/babylon101/sprites
  24406. */
  24407. _this.spriteManagers = new Array();
  24408. // Skeletons
  24409. _this._skeletonsEnabled = true;
  24410. // Lens flares
  24411. /**
  24412. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24413. */
  24414. _this.lensFlaresEnabled = true;
  24415. // Collisions
  24416. /**
  24417. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24418. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24419. */
  24420. _this.collisionsEnabled = true;
  24421. /**
  24422. * Defines the gravity applied to this scene (used only for collisions)
  24423. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24424. */
  24425. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24426. // Postprocesses
  24427. /**
  24428. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24429. */
  24430. _this.postProcessesEnabled = true;
  24431. /**
  24432. * The list of postprocesses added to the scene
  24433. */
  24434. _this.postProcesses = new Array();
  24435. // Customs render targets
  24436. /**
  24437. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24438. */
  24439. _this.renderTargetsEnabled = true;
  24440. /**
  24441. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24442. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24443. */
  24444. _this.dumpNextRenderTargets = false;
  24445. /**
  24446. * The list of user defined render targets added to the scene
  24447. */
  24448. _this.customRenderTargets = new Array();
  24449. /**
  24450. * Gets the list of meshes imported to the scene through SceneLoader
  24451. */
  24452. _this.importedMeshesFiles = new Array();
  24453. // Probes
  24454. /**
  24455. * Gets or sets a boolean indicating if probes are enabled on this scene
  24456. */
  24457. _this.probesEnabled = true;
  24458. /**
  24459. * The list of reflection probes added to the scene
  24460. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24461. */
  24462. _this.reflectionProbes = new Array();
  24463. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24464. // Procedural textures
  24465. /**
  24466. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24467. */
  24468. _this.proceduralTexturesEnabled = true;
  24469. /**
  24470. * The list of procedural textures added to the scene
  24471. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24472. */
  24473. _this.proceduralTextures = new Array();
  24474. /**
  24475. * The list of sound tracks added to the scene
  24476. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24477. */
  24478. _this.soundTracks = new Array();
  24479. _this._audioEnabled = true;
  24480. _this._headphone = false;
  24481. // Performance counters
  24482. _this._totalVertices = new BABYLON.PerfCounter();
  24483. /** @hidden */
  24484. _this._activeIndices = new BABYLON.PerfCounter();
  24485. /** @hidden */
  24486. _this._activeParticles = new BABYLON.PerfCounter();
  24487. /** @hidden */
  24488. _this._activeBones = new BABYLON.PerfCounter();
  24489. _this._animationTime = 0;
  24490. /**
  24491. * Gets or sets a general scale for animation speed
  24492. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24493. */
  24494. _this.animationTimeScale = 1;
  24495. _this._renderId = 0;
  24496. _this._executeWhenReadyTimeoutId = -1;
  24497. _this._intermediateRendering = false;
  24498. _this._viewUpdateFlag = -1;
  24499. _this._projectionUpdateFlag = -1;
  24500. _this._alternateViewUpdateFlag = -1;
  24501. _this._alternateProjectionUpdateFlag = -1;
  24502. /** @hidden */
  24503. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24504. _this._activeRequests = new Array();
  24505. _this._pendingData = new Array();
  24506. _this._isDisposed = false;
  24507. /**
  24508. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24509. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24510. */
  24511. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24512. _this._activeMeshes = new BABYLON.SmartArray(256);
  24513. _this._processedMaterials = new BABYLON.SmartArray(256);
  24514. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24515. /** @hidden */
  24516. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24517. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24518. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24519. /** @hidden */
  24520. _this._activeAnimatables = new Array();
  24521. _this._transformMatrix = BABYLON.Matrix.Zero();
  24522. _this._useAlternateCameraConfiguration = false;
  24523. _this._alternateRendering = false;
  24524. /**
  24525. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24526. * This is useful if there are more lights that the maximum simulteanous authorized
  24527. */
  24528. _this.requireLightSorting = false;
  24529. _this._depthRenderer = {};
  24530. /**
  24531. * Backing store of defined scene components.
  24532. */
  24533. _this._components = [];
  24534. /**
  24535. * List of components to register on the next registration step.
  24536. */
  24537. _this._transientComponents = [];
  24538. /**
  24539. * Defines the actions happening during the per mesh ready checks.
  24540. */
  24541. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24542. /**
  24543. * Defines the actions happening during the per camera render target step.
  24544. */
  24545. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24546. /**
  24547. * Defines the actions happening just before the active camera is drawing.
  24548. */
  24549. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24550. /**
  24551. * Defines the actions happening just before a rendering group is drawing.
  24552. */
  24553. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24554. /**
  24555. * Defines the actions happening just after a rendering group has been drawn.
  24556. */
  24557. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24558. /**
  24559. * Defines the actions happening just after the active camera has been drawn.
  24560. */
  24561. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24562. _this._activeMeshesFrozen = false;
  24563. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24564. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24565. _this._engine.scenes.push(_this);
  24566. _this._uid = null;
  24567. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24568. if (BABYLON.PostProcessManager) {
  24569. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24570. }
  24571. if (BABYLON.OutlineRenderer) {
  24572. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24573. }
  24574. if (BABYLON.Tools.IsWindowObjectExist()) {
  24575. _this.attachControl();
  24576. }
  24577. //simplification queue
  24578. if (BABYLON.SimplificationQueue) {
  24579. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24580. }
  24581. //collision coordinator initialization. For now legacy per default.
  24582. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24583. // Uniform Buffer
  24584. _this._createUbo();
  24585. // Default Image processing definition
  24586. if (BABYLON.ImageProcessingConfiguration) {
  24587. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24588. }
  24589. return _this;
  24590. }
  24591. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24592. /** The fog is deactivated */
  24593. get: function () {
  24594. return Scene._FOGMODE_NONE;
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24600. /** The fog density is following an exponential function */
  24601. get: function () {
  24602. return Scene._FOGMODE_EXP;
  24603. },
  24604. enumerable: true,
  24605. configurable: true
  24606. });
  24607. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24608. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24609. get: function () {
  24610. return Scene._FOGMODE_EXP2;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24616. /** The fog density is following a linear function. */
  24617. get: function () {
  24618. return Scene._FOGMODE_LINEAR;
  24619. },
  24620. enumerable: true,
  24621. configurable: true
  24622. });
  24623. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24624. /**
  24625. * Texture used in all pbr material as the reflection texture.
  24626. * As in the majority of the scene they are the same (exception for multi room and so on),
  24627. * this is easier to reference from here than from all the materials.
  24628. */
  24629. get: function () {
  24630. return this._environmentTexture;
  24631. },
  24632. /**
  24633. * Texture used in all pbr material as the reflection texture.
  24634. * As in the majority of the scene they are the same (exception for multi room and so on),
  24635. * this is easier to set here than in all the materials.
  24636. */
  24637. set: function (value) {
  24638. if (this._environmentTexture === value) {
  24639. return;
  24640. }
  24641. this._environmentTexture = value;
  24642. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24643. },
  24644. enumerable: true,
  24645. configurable: true
  24646. });
  24647. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24648. /**
  24649. * Default image processing configuration used either in the rendering
  24650. * Forward main pass or through the imageProcessingPostProcess if present.
  24651. * As in the majority of the scene they are the same (exception for multi camera),
  24652. * this is easier to reference from here than from all the materials and post process.
  24653. *
  24654. * No setter as we it is a shared configuration, you can set the values instead.
  24655. */
  24656. get: function () {
  24657. return this._imageProcessingConfiguration;
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24663. get: function () {
  24664. return this._forceWireframe;
  24665. },
  24666. /**
  24667. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24668. */
  24669. set: function (value) {
  24670. if (this._forceWireframe === value) {
  24671. return;
  24672. }
  24673. this._forceWireframe = value;
  24674. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24675. },
  24676. enumerable: true,
  24677. configurable: true
  24678. });
  24679. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24680. get: function () {
  24681. return this._forcePointsCloud;
  24682. },
  24683. /**
  24684. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24685. */
  24686. set: function (value) {
  24687. if (this._forcePointsCloud === value) {
  24688. return;
  24689. }
  24690. this._forcePointsCloud = value;
  24691. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24692. },
  24693. enumerable: true,
  24694. configurable: true
  24695. });
  24696. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24697. /**
  24698. * Gets or sets the animation properties override
  24699. */
  24700. get: function () {
  24701. return this._animationPropertiesOverride;
  24702. },
  24703. set: function (value) {
  24704. this._animationPropertiesOverride = value;
  24705. },
  24706. enumerable: true,
  24707. configurable: true
  24708. });
  24709. Object.defineProperty(Scene.prototype, "onDispose", {
  24710. /** Sets a function to be executed when this scene is disposed. */
  24711. set: function (callback) {
  24712. if (this._onDisposeObserver) {
  24713. this.onDisposeObservable.remove(this._onDisposeObserver);
  24714. }
  24715. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24716. },
  24717. enumerable: true,
  24718. configurable: true
  24719. });
  24720. Object.defineProperty(Scene.prototype, "beforeRender", {
  24721. /** Sets a function to be executed before rendering this scene */
  24722. set: function (callback) {
  24723. if (this._onBeforeRenderObserver) {
  24724. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24725. }
  24726. if (callback) {
  24727. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24728. }
  24729. },
  24730. enumerable: true,
  24731. configurable: true
  24732. });
  24733. Object.defineProperty(Scene.prototype, "afterRender", {
  24734. /** Sets a function to be executed after rendering this scene */
  24735. set: function (callback) {
  24736. if (this._onAfterRenderObserver) {
  24737. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24738. }
  24739. if (callback) {
  24740. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24741. }
  24742. },
  24743. enumerable: true,
  24744. configurable: true
  24745. });
  24746. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24747. /** Sets a function to be executed before rendering a camera*/
  24748. set: function (callback) {
  24749. if (this._onBeforeCameraRenderObserver) {
  24750. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24751. }
  24752. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24753. },
  24754. enumerable: true,
  24755. configurable: true
  24756. });
  24757. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24758. /** Sets a function to be executed after rendering a camera*/
  24759. set: function (callback) {
  24760. if (this._onAfterCameraRenderObserver) {
  24761. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24762. }
  24763. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24769. /**
  24770. * Gets the gamepad manager associated with the scene
  24771. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24772. */
  24773. get: function () {
  24774. if (!this._gamepadManager) {
  24775. this._gamepadManager = new BABYLON.GamepadManager(this);
  24776. }
  24777. return this._gamepadManager;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24783. /**
  24784. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24785. */
  24786. get: function () {
  24787. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24788. },
  24789. enumerable: true,
  24790. configurable: true
  24791. });
  24792. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24793. get: function () {
  24794. return this._useRightHandedSystem;
  24795. },
  24796. /**
  24797. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24798. */
  24799. set: function (value) {
  24800. if (this._useRightHandedSystem === value) {
  24801. return;
  24802. }
  24803. this._useRightHandedSystem = value;
  24804. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24805. },
  24806. enumerable: true,
  24807. configurable: true
  24808. });
  24809. /**
  24810. * Sets the step Id used by deterministic lock step
  24811. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24812. * @param newStepId defines the step Id
  24813. */
  24814. Scene.prototype.setStepId = function (newStepId) {
  24815. this._currentStepId = newStepId;
  24816. };
  24817. ;
  24818. /**
  24819. * Gets the step Id used by deterministic lock step
  24820. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24821. * @returns the step Id
  24822. */
  24823. Scene.prototype.getStepId = function () {
  24824. return this._currentStepId;
  24825. };
  24826. ;
  24827. /**
  24828. * Gets the internal step used by deterministic lock step
  24829. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24830. * @returns the internal step
  24831. */
  24832. Scene.prototype.getInternalStep = function () {
  24833. return this._currentInternalStep;
  24834. };
  24835. ;
  24836. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24837. get: function () {
  24838. return this._fogEnabled;
  24839. },
  24840. /**
  24841. * Gets or sets a boolean indicating if fog is enabled on this scene
  24842. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24843. */
  24844. set: function (value) {
  24845. if (this._fogEnabled === value) {
  24846. return;
  24847. }
  24848. this._fogEnabled = value;
  24849. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24850. },
  24851. enumerable: true,
  24852. configurable: true
  24853. });
  24854. Object.defineProperty(Scene.prototype, "fogMode", {
  24855. get: function () {
  24856. return this._fogMode;
  24857. },
  24858. /**
  24859. * Gets or sets the fog mode to use
  24860. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24861. */
  24862. set: function (value) {
  24863. if (this._fogMode === value) {
  24864. return;
  24865. }
  24866. this._fogMode = value;
  24867. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24868. },
  24869. enumerable: true,
  24870. configurable: true
  24871. });
  24872. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24873. get: function () {
  24874. return this._shadowsEnabled;
  24875. },
  24876. /**
  24877. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24878. */
  24879. set: function (value) {
  24880. if (this._shadowsEnabled === value) {
  24881. return;
  24882. }
  24883. this._shadowsEnabled = value;
  24884. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24885. },
  24886. enumerable: true,
  24887. configurable: true
  24888. });
  24889. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24890. get: function () {
  24891. return this._lightsEnabled;
  24892. },
  24893. /**
  24894. * Gets or sets a boolean indicating if lights are enabled on this scene
  24895. */
  24896. set: function (value) {
  24897. if (this._lightsEnabled === value) {
  24898. return;
  24899. }
  24900. this._lightsEnabled = value;
  24901. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24902. },
  24903. enumerable: true,
  24904. configurable: true
  24905. });
  24906. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24907. /** The default material used on meshes when no material is affected */
  24908. get: function () {
  24909. if (!this._defaultMaterial) {
  24910. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24911. }
  24912. return this._defaultMaterial;
  24913. },
  24914. /** The default material used on meshes when no material is affected */
  24915. set: function (value) {
  24916. this._defaultMaterial = value;
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24922. get: function () {
  24923. return this._texturesEnabled;
  24924. },
  24925. /**
  24926. * Gets or sets a boolean indicating if textures are enabled on this scene
  24927. */
  24928. set: function (value) {
  24929. if (this._texturesEnabled === value) {
  24930. return;
  24931. }
  24932. this._texturesEnabled = value;
  24933. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24934. },
  24935. enumerable: true,
  24936. configurable: true
  24937. });
  24938. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24939. get: function () {
  24940. return this._skeletonsEnabled;
  24941. },
  24942. /**
  24943. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24944. */
  24945. set: function (value) {
  24946. if (this._skeletonsEnabled === value) {
  24947. return;
  24948. }
  24949. this._skeletonsEnabled = value;
  24950. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24951. },
  24952. enumerable: true,
  24953. configurable: true
  24954. });
  24955. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24956. /**
  24957. * Gets the postprocess render pipeline manager
  24958. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24959. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24960. */
  24961. get: function () {
  24962. if (!this._postProcessRenderPipelineManager) {
  24963. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24964. }
  24965. return this._postProcessRenderPipelineManager;
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24971. /**
  24972. * Gets the main soundtrack associated with the scene
  24973. */
  24974. get: function () {
  24975. if (!this._mainSoundTrack) {
  24976. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24977. }
  24978. return this._mainSoundTrack;
  24979. },
  24980. enumerable: true,
  24981. configurable: true
  24982. });
  24983. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24984. /** @hidden */
  24985. get: function () {
  24986. return this._alternateRendering;
  24987. },
  24988. enumerable: true,
  24989. configurable: true
  24990. });
  24991. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24992. /**
  24993. * Gets the list of frustum planes (built from the active camera)
  24994. */
  24995. get: function () {
  24996. return this._frustumPlanes;
  24997. },
  24998. enumerable: true,
  24999. configurable: true
  25000. });
  25001. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  25002. /**
  25003. * Gets the current geometry buffer associated to the scene.
  25004. */
  25005. get: function () {
  25006. return this._geometryBufferRenderer;
  25007. },
  25008. /**
  25009. * Sets the current geometry buffer for the scene.
  25010. */
  25011. set: function (geometryBufferRenderer) {
  25012. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  25013. this._geometryBufferRenderer = geometryBufferRenderer;
  25014. }
  25015. },
  25016. enumerable: true,
  25017. configurable: true
  25018. });
  25019. /**
  25020. * Registers the transient components if needed.
  25021. */
  25022. Scene.prototype._registerTransientComponents = function () {
  25023. // Register components that have been associated lately to the scene.
  25024. if (this._transientComponents.length > 0) {
  25025. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25026. var component = _a[_i];
  25027. component.register();
  25028. }
  25029. this._transientComponents = [];
  25030. }
  25031. };
  25032. /**
  25033. * Add a component to the scene.
  25034. * Note that the ccomponent could be registered on th next frame if this is called after
  25035. * the register component stage.
  25036. * @param component Defines the component to add to the scene
  25037. */
  25038. Scene.prototype._addComponent = function (component) {
  25039. this._components.push(component);
  25040. this._transientComponents.push(component);
  25041. };
  25042. /**
  25043. * Gets a component from the scene.
  25044. * @param name defines the name of the component to retrieve
  25045. * @returns the component or null if not present
  25046. */
  25047. Scene.prototype._getComponent = function (name) {
  25048. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25049. var component = _a[_i];
  25050. if (component.name === name) {
  25051. return component;
  25052. }
  25053. }
  25054. return null;
  25055. };
  25056. Object.defineProperty(Scene.prototype, "debugLayer", {
  25057. /**
  25058. * Gets the debug layer (aka Inspector) associated with the scene
  25059. * @see http://doc.babylonjs.com/features/playground_debuglayer
  25060. */
  25061. get: function () {
  25062. if (!this._debugLayer) {
  25063. this._debugLayer = new BABYLON.DebugLayer(this);
  25064. }
  25065. return this._debugLayer;
  25066. },
  25067. enumerable: true,
  25068. configurable: true
  25069. });
  25070. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25071. /**
  25072. * Gets a boolean indicating if collisions are processed on a web worker
  25073. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25074. */
  25075. get: function () {
  25076. return this._workerCollisions;
  25077. },
  25078. set: function (enabled) {
  25079. if (!BABYLON.CollisionCoordinatorLegacy) {
  25080. return;
  25081. }
  25082. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25083. this._workerCollisions = enabled;
  25084. if (this.collisionCoordinator) {
  25085. this.collisionCoordinator.destroy();
  25086. }
  25087. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25088. this.collisionCoordinator.init(this);
  25089. },
  25090. enumerable: true,
  25091. configurable: true
  25092. });
  25093. Object.defineProperty(Scene.prototype, "selectionOctree", {
  25094. /**
  25095. * Gets the octree used to boost mesh selection (picking)
  25096. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25097. */
  25098. get: function () {
  25099. return this._selectionOctree;
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25105. /**
  25106. * Gets the mesh that is currently under the pointer
  25107. */
  25108. get: function () {
  25109. return this._pointerOverMesh;
  25110. },
  25111. enumerable: true,
  25112. configurable: true
  25113. });
  25114. Object.defineProperty(Scene.prototype, "pointerX", {
  25115. /**
  25116. * Gets the current on-screen X position of the pointer
  25117. */
  25118. get: function () {
  25119. return this._pointerX;
  25120. },
  25121. enumerable: true,
  25122. configurable: true
  25123. });
  25124. Object.defineProperty(Scene.prototype, "pointerY", {
  25125. /**
  25126. * Gets the current on-screen Y position of the pointer
  25127. */
  25128. get: function () {
  25129. return this._pointerY;
  25130. },
  25131. enumerable: true,
  25132. configurable: true
  25133. });
  25134. /**
  25135. * Gets the cached material (ie. the latest rendered one)
  25136. * @returns the cached material
  25137. */
  25138. Scene.prototype.getCachedMaterial = function () {
  25139. return this._cachedMaterial;
  25140. };
  25141. /**
  25142. * Gets the cached effect (ie. the latest rendered one)
  25143. * @returns the cached effect
  25144. */
  25145. Scene.prototype.getCachedEffect = function () {
  25146. return this._cachedEffect;
  25147. };
  25148. /**
  25149. * Gets the cached visibility state (ie. the latest rendered one)
  25150. * @returns the cached visibility state
  25151. */
  25152. Scene.prototype.getCachedVisibility = function () {
  25153. return this._cachedVisibility;
  25154. };
  25155. /**
  25156. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25157. * @param material defines the current material
  25158. * @param effect defines the current effect
  25159. * @param visibility defines the current visibility state
  25160. * @returns true if one parameter is not cached
  25161. */
  25162. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25163. if (visibility === void 0) { visibility = 1; }
  25164. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25165. };
  25166. /**
  25167. * Gets the bounding box renderer associated with the scene
  25168. * @returns a BoundingBoxRenderer
  25169. */
  25170. Scene.prototype.getBoundingBoxRenderer = function () {
  25171. if (!this._boundingBoxRenderer) {
  25172. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  25173. }
  25174. return this._boundingBoxRenderer;
  25175. };
  25176. /**
  25177. * Gets the outline renderer associated with the scene
  25178. * @returns a OutlineRenderer
  25179. */
  25180. Scene.prototype.getOutlineRenderer = function () {
  25181. return this._outlineRenderer;
  25182. };
  25183. /**
  25184. * Gets the engine associated with the scene
  25185. * @returns an Engine
  25186. */
  25187. Scene.prototype.getEngine = function () {
  25188. return this._engine;
  25189. };
  25190. /**
  25191. * Gets the total number of vertices rendered per frame
  25192. * @returns the total number of vertices rendered per frame
  25193. */
  25194. Scene.prototype.getTotalVertices = function () {
  25195. return this._totalVertices.current;
  25196. };
  25197. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25198. /**
  25199. * Gets the performance counter for total vertices
  25200. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25201. */
  25202. get: function () {
  25203. return this._totalVertices;
  25204. },
  25205. enumerable: true,
  25206. configurable: true
  25207. });
  25208. /**
  25209. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25210. * @returns the total number of active indices rendered per frame
  25211. */
  25212. Scene.prototype.getActiveIndices = function () {
  25213. return this._activeIndices.current;
  25214. };
  25215. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25216. /**
  25217. * Gets the performance counter for active indices
  25218. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25219. */
  25220. get: function () {
  25221. return this._activeIndices;
  25222. },
  25223. enumerable: true,
  25224. configurable: true
  25225. });
  25226. /**
  25227. * Gets the total number of active particles rendered per frame
  25228. * @returns the total number of active particles rendered per frame
  25229. */
  25230. Scene.prototype.getActiveParticles = function () {
  25231. return this._activeParticles.current;
  25232. };
  25233. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25234. /**
  25235. * Gets the performance counter for active particles
  25236. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25237. */
  25238. get: function () {
  25239. return this._activeParticles;
  25240. },
  25241. enumerable: true,
  25242. configurable: true
  25243. });
  25244. /**
  25245. * Gets the total number of active bones rendered per frame
  25246. * @returns the total number of active bones rendered per frame
  25247. */
  25248. Scene.prototype.getActiveBones = function () {
  25249. return this._activeBones.current;
  25250. };
  25251. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25252. /**
  25253. * Gets the performance counter for active bones
  25254. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25255. */
  25256. get: function () {
  25257. return this._activeBones;
  25258. },
  25259. enumerable: true,
  25260. configurable: true
  25261. });
  25262. /** @hidden */
  25263. Scene.prototype.getInterFramePerfCounter = function () {
  25264. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25265. return 0;
  25266. };
  25267. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25268. /** @hidden */
  25269. get: function () {
  25270. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25271. return null;
  25272. },
  25273. enumerable: true,
  25274. configurable: true
  25275. });
  25276. /** @hidden */
  25277. Scene.prototype.getLastFrameDuration = function () {
  25278. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25279. return 0;
  25280. };
  25281. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25282. /** @hidden */
  25283. get: function () {
  25284. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25285. return null;
  25286. },
  25287. enumerable: true,
  25288. configurable: true
  25289. });
  25290. /** @hidden */
  25291. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25292. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25293. return 0;
  25294. };
  25295. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25296. /** @hidden */
  25297. get: function () {
  25298. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25299. return null;
  25300. },
  25301. enumerable: true,
  25302. configurable: true
  25303. });
  25304. /**
  25305. * Gets the array of active meshes
  25306. * @returns an array of AbstractMesh
  25307. */
  25308. Scene.prototype.getActiveMeshes = function () {
  25309. return this._activeMeshes;
  25310. };
  25311. /** @hidden */
  25312. Scene.prototype.getRenderTargetsDuration = function () {
  25313. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25314. return 0;
  25315. };
  25316. /** @hidden */
  25317. Scene.prototype.getRenderDuration = function () {
  25318. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25319. return 0;
  25320. };
  25321. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25322. /** @hidden */
  25323. get: function () {
  25324. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25325. return null;
  25326. },
  25327. enumerable: true,
  25328. configurable: true
  25329. });
  25330. /** @hidden */
  25331. Scene.prototype.getParticlesDuration = function () {
  25332. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25333. return 0;
  25334. };
  25335. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25336. /** @hidden */
  25337. get: function () {
  25338. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25339. return null;
  25340. },
  25341. enumerable: true,
  25342. configurable: true
  25343. });
  25344. /** @hidden */
  25345. Scene.prototype.getSpritesDuration = function () {
  25346. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25347. return 0;
  25348. };
  25349. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25350. /** @hidden */
  25351. get: function () {
  25352. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25353. return null;
  25354. },
  25355. enumerable: true,
  25356. configurable: true
  25357. });
  25358. /**
  25359. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25360. * @returns a number
  25361. */
  25362. Scene.prototype.getAnimationRatio = function () {
  25363. return this._animationRatio;
  25364. };
  25365. /**
  25366. * Gets an unique Id for the current frame
  25367. * @returns a number
  25368. */
  25369. Scene.prototype.getRenderId = function () {
  25370. return this._renderId;
  25371. };
  25372. /** Call this function if you want to manually increment the render Id*/
  25373. Scene.prototype.incrementRenderId = function () {
  25374. this._renderId++;
  25375. };
  25376. Scene.prototype._updatePointerPosition = function (evt) {
  25377. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25378. if (!canvasRect) {
  25379. return;
  25380. }
  25381. this._pointerX = evt.clientX - canvasRect.left;
  25382. this._pointerY = evt.clientY - canvasRect.top;
  25383. this._unTranslatedPointerX = this._pointerX;
  25384. this._unTranslatedPointerY = this._pointerY;
  25385. };
  25386. Scene.prototype._createUbo = function () {
  25387. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25388. this._sceneUbo.addUniform("viewProjection", 16);
  25389. this._sceneUbo.addUniform("view", 16);
  25390. };
  25391. Scene.prototype._createAlternateUbo = function () {
  25392. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25393. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25394. this._alternateSceneUbo.addUniform("view", 16);
  25395. };
  25396. // Pointers handling
  25397. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25398. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25399. if (result) {
  25400. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25401. }
  25402. return result;
  25403. };
  25404. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25405. if (pointerInfo.pickInfo) {
  25406. if (!pointerInfo.pickInfo.ray) {
  25407. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25408. }
  25409. }
  25410. };
  25411. /**
  25412. * Use this method to simulate a pointer move on a mesh
  25413. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25414. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25415. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25416. * @returns the current scene
  25417. */
  25418. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25419. var evt = new PointerEvent("pointermove", pointerEventInit);
  25420. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25421. return this;
  25422. }
  25423. return this._processPointerMove(pickResult, evt);
  25424. };
  25425. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25426. var canvas = this._engine.getRenderingCanvas();
  25427. if (!canvas) {
  25428. return this;
  25429. }
  25430. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25431. this.setPointerOverSprite(null);
  25432. this.setPointerOverMesh(pickResult.pickedMesh);
  25433. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25434. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25435. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25436. }
  25437. else {
  25438. canvas.style.cursor = this.hoverCursor;
  25439. }
  25440. }
  25441. else {
  25442. canvas.style.cursor = this.defaultCursor;
  25443. }
  25444. }
  25445. else {
  25446. this.setPointerOverMesh(null);
  25447. // Sprites
  25448. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25449. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25450. this.setPointerOverSprite(pickResult.pickedSprite);
  25451. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25452. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25453. }
  25454. else {
  25455. canvas.style.cursor = this.hoverCursor;
  25456. }
  25457. }
  25458. else {
  25459. this.setPointerOverSprite(null);
  25460. // Restore pointer
  25461. canvas.style.cursor = this.defaultCursor;
  25462. }
  25463. }
  25464. if (pickResult) {
  25465. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25466. if (this.onPointerMove) {
  25467. this.onPointerMove(evt, pickResult, type);
  25468. }
  25469. if (this.onPointerObservable.hasObservers()) {
  25470. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25471. this._setRayOnPointerInfo(pi);
  25472. this.onPointerObservable.notifyObservers(pi, type);
  25473. }
  25474. }
  25475. return this;
  25476. };
  25477. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25478. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25479. if (pickResult) {
  25480. pi.ray = pickResult.ray;
  25481. }
  25482. this.onPrePointerObservable.notifyObservers(pi, type);
  25483. if (pi.skipOnPointerObservable) {
  25484. return true;
  25485. }
  25486. else {
  25487. return false;
  25488. }
  25489. };
  25490. /**
  25491. * Use this method to simulate a pointer down on a mesh
  25492. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25493. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25494. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25495. * @returns the current scene
  25496. */
  25497. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25498. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25499. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25500. return this;
  25501. }
  25502. return this._processPointerDown(pickResult, evt);
  25503. };
  25504. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25505. var _this = this;
  25506. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25507. this._pickedDownMesh = pickResult.pickedMesh;
  25508. var actionManager = pickResult.pickedMesh.actionManager;
  25509. if (actionManager) {
  25510. if (actionManager.hasPickTriggers) {
  25511. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25512. switch (evt.button) {
  25513. case 0:
  25514. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25515. break;
  25516. case 1:
  25517. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25518. break;
  25519. case 2:
  25520. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25521. break;
  25522. }
  25523. }
  25524. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25525. window.setTimeout(function () {
  25526. 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);
  25527. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25528. if (_this._totalPointersPressed !== 0 &&
  25529. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25530. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25531. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25532. _this._startingPointerTime = 0;
  25533. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25534. }
  25535. }
  25536. }, Scene.LongPressDelay);
  25537. }
  25538. }
  25539. }
  25540. if (pickResult) {
  25541. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25542. if (this.onPointerDown) {
  25543. this.onPointerDown(evt, pickResult, type);
  25544. }
  25545. if (this.onPointerObservable.hasObservers()) {
  25546. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25547. this._setRayOnPointerInfo(pi);
  25548. this.onPointerObservable.notifyObservers(pi, type);
  25549. }
  25550. }
  25551. return this;
  25552. };
  25553. /**
  25554. * Use this method to simulate a pointer up on a mesh
  25555. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25556. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25557. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25558. * @returns the current scene
  25559. */
  25560. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25561. var evt = new PointerEvent("pointerup", pointerEventInit);
  25562. var clickInfo = new ClickInfo();
  25563. clickInfo.singleClick = true;
  25564. clickInfo.ignore = true;
  25565. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25566. return this;
  25567. }
  25568. return this._processPointerUp(pickResult, evt, clickInfo);
  25569. };
  25570. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25571. if (pickResult && pickResult && pickResult.pickedMesh) {
  25572. this._pickedUpMesh = pickResult.pickedMesh;
  25573. if (this._pickedDownMesh === this._pickedUpMesh) {
  25574. if (this.onPointerPick) {
  25575. this.onPointerPick(evt, pickResult);
  25576. }
  25577. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25578. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25579. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25580. this._setRayOnPointerInfo(pi);
  25581. this.onPointerObservable.notifyObservers(pi, type_1);
  25582. }
  25583. }
  25584. if (pickResult.pickedMesh.actionManager) {
  25585. if (clickInfo.ignore) {
  25586. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25587. }
  25588. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25589. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25590. }
  25591. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25592. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25593. }
  25594. }
  25595. }
  25596. if (this._pickedDownMesh &&
  25597. this._pickedDownMesh.actionManager &&
  25598. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25599. this._pickedDownMesh !== this._pickedUpMesh) {
  25600. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25601. }
  25602. var type = BABYLON.PointerEventTypes.POINTERUP;
  25603. if (this.onPointerObservable.hasObservers()) {
  25604. if (!clickInfo.ignore) {
  25605. if (!clickInfo.hasSwiped) {
  25606. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25607. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25608. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25609. this._setRayOnPointerInfo(pi);
  25610. this.onPointerObservable.notifyObservers(pi, type_2);
  25611. }
  25612. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25613. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25614. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25615. this._setRayOnPointerInfo(pi);
  25616. this.onPointerObservable.notifyObservers(pi, type_3);
  25617. }
  25618. }
  25619. }
  25620. else {
  25621. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25622. this._setRayOnPointerInfo(pi);
  25623. this.onPointerObservable.notifyObservers(pi, type);
  25624. }
  25625. }
  25626. if (this.onPointerUp) {
  25627. this.onPointerUp(evt, pickResult, type);
  25628. }
  25629. return this;
  25630. };
  25631. /**
  25632. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25633. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25634. * @returns true if the pointer was captured
  25635. */
  25636. Scene.prototype.isPointerCaptured = function (pointerId) {
  25637. if (pointerId === void 0) { pointerId = 0; }
  25638. return this._pointerCaptures[pointerId];
  25639. };
  25640. /**
  25641. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25642. * @param attachUp defines if you want to attach events to pointerup
  25643. * @param attachDown defines if you want to attach events to pointerdown
  25644. * @param attachMove defines if you want to attach events to pointermove
  25645. */
  25646. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25647. var _this = this;
  25648. if (attachUp === void 0) { attachUp = true; }
  25649. if (attachDown === void 0) { attachDown = true; }
  25650. if (attachMove === void 0) { attachMove = true; }
  25651. this._initActionManager = function (act, clickInfo) {
  25652. if (!_this._meshPickProceed) {
  25653. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25654. _this._currentPickResult = pickResult;
  25655. if (pickResult) {
  25656. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25657. }
  25658. _this._meshPickProceed = true;
  25659. }
  25660. return act;
  25661. };
  25662. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25663. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25664. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25665. btn !== _this._previousButtonPressed) {
  25666. _this._doubleClickOccured = false;
  25667. clickInfo.singleClick = true;
  25668. clickInfo.ignore = false;
  25669. cb(clickInfo, _this._currentPickResult);
  25670. }
  25671. };
  25672. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25673. var clickInfo = new ClickInfo();
  25674. _this._currentPickResult = null;
  25675. var act = null;
  25676. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25677. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25678. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25679. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25680. act = _this._initActionManager(act, clickInfo);
  25681. if (act)
  25682. checkPicking = act.hasPickTriggers;
  25683. }
  25684. if (checkPicking) {
  25685. var btn = evt.button;
  25686. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25687. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25688. if (!clickInfo.hasSwiped) {
  25689. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25690. if (!checkSingleClickImmediately) {
  25691. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25692. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25693. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25694. act = _this._initActionManager(act, clickInfo);
  25695. if (act)
  25696. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25697. }
  25698. }
  25699. if (checkSingleClickImmediately) {
  25700. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25701. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25702. btn !== _this._previousButtonPressed) {
  25703. clickInfo.singleClick = true;
  25704. cb(clickInfo, _this._currentPickResult);
  25705. }
  25706. }
  25707. // at least one double click is required to be check and exclusive double click is enabled
  25708. else {
  25709. // wait that no double click has been raised during the double click delay
  25710. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25711. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25712. }
  25713. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25714. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25715. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25716. act = _this._initActionManager(act, clickInfo);
  25717. if (act)
  25718. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25719. }
  25720. if (checkDoubleClick) {
  25721. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25722. if (btn === _this._previousButtonPressed &&
  25723. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25724. !_this._doubleClickOccured) {
  25725. // pointer has not moved for 2 clicks, it's a double click
  25726. if (!clickInfo.hasSwiped &&
  25727. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25728. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25729. _this._previousStartingPointerTime = 0;
  25730. _this._doubleClickOccured = true;
  25731. clickInfo.doubleClick = true;
  25732. clickInfo.ignore = false;
  25733. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25734. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25735. }
  25736. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25737. cb(clickInfo, _this._currentPickResult);
  25738. }
  25739. // if the two successive clicks are too far, it's just two simple clicks
  25740. else {
  25741. _this._doubleClickOccured = false;
  25742. _this._previousStartingPointerTime = _this._startingPointerTime;
  25743. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25744. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25745. _this._previousButtonPressed = btn;
  25746. if (Scene.ExclusiveDoubleClickMode) {
  25747. if (_this._previousDelayedSimpleClickTimeout) {
  25748. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25749. }
  25750. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25751. cb(clickInfo, _this._previousPickResult);
  25752. }
  25753. else {
  25754. cb(clickInfo, _this._currentPickResult);
  25755. }
  25756. }
  25757. }
  25758. // just the first click of the double has been raised
  25759. else {
  25760. _this._doubleClickOccured = false;
  25761. _this._previousStartingPointerTime = _this._startingPointerTime;
  25762. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25763. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25764. _this._previousButtonPressed = btn;
  25765. }
  25766. }
  25767. }
  25768. }
  25769. clickInfo.ignore = true;
  25770. cb(clickInfo, _this._currentPickResult);
  25771. };
  25772. this._spritePredicate = function (sprite) {
  25773. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25774. };
  25775. this._onPointerMove = function (evt) {
  25776. _this._updatePointerPosition(evt);
  25777. // PreObservable support
  25778. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25779. return;
  25780. }
  25781. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25782. return;
  25783. }
  25784. if (!_this.pointerMovePredicate) {
  25785. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25786. }
  25787. // Meshes
  25788. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25789. _this._processPointerMove(pickResult, evt);
  25790. };
  25791. this._onPointerDown = function (evt) {
  25792. _this._totalPointersPressed++;
  25793. _this._pickedDownMesh = null;
  25794. _this._meshPickProceed = false;
  25795. _this._updatePointerPosition(evt);
  25796. if (_this.preventDefaultOnPointerDown && canvas) {
  25797. evt.preventDefault();
  25798. canvas.focus();
  25799. }
  25800. // PreObservable support
  25801. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25802. return;
  25803. }
  25804. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25805. return;
  25806. }
  25807. _this._pointerCaptures[evt.pointerId] = true;
  25808. _this._startingPointerPosition.x = _this._pointerX;
  25809. _this._startingPointerPosition.y = _this._pointerY;
  25810. _this._startingPointerTime = Date.now();
  25811. if (!_this.pointerDownPredicate) {
  25812. _this.pointerDownPredicate = function (mesh) {
  25813. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25814. };
  25815. }
  25816. // Meshes
  25817. _this._pickedDownMesh = null;
  25818. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25819. _this._processPointerDown(pickResult, evt);
  25820. // Sprites
  25821. _this._pickedDownSprite = null;
  25822. if (_this.spriteManagers.length > 0) {
  25823. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25824. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25825. if (pickResult.pickedSprite.actionManager) {
  25826. _this._pickedDownSprite = pickResult.pickedSprite;
  25827. switch (evt.button) {
  25828. case 0:
  25829. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25830. break;
  25831. case 1:
  25832. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25833. break;
  25834. case 2:
  25835. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25836. break;
  25837. }
  25838. if (pickResult.pickedSprite.actionManager) {
  25839. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25840. }
  25841. }
  25842. }
  25843. }
  25844. };
  25845. this._onPointerUp = function (evt) {
  25846. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25847. return; // So we need to test it the pointer down was pressed before.
  25848. }
  25849. _this._totalPointersPressed--;
  25850. _this._pickedUpMesh = null;
  25851. _this._meshPickProceed = false;
  25852. _this._updatePointerPosition(evt);
  25853. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25854. // PreObservable support
  25855. if (_this.onPrePointerObservable.hasObservers()) {
  25856. if (!clickInfo.ignore) {
  25857. if (!clickInfo.hasSwiped) {
  25858. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25859. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25860. return;
  25861. }
  25862. }
  25863. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25864. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25865. return;
  25866. }
  25867. }
  25868. }
  25869. }
  25870. else {
  25871. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25872. return;
  25873. }
  25874. }
  25875. }
  25876. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25877. return;
  25878. }
  25879. _this._pointerCaptures[evt.pointerId] = false;
  25880. if (!_this.pointerUpPredicate) {
  25881. _this.pointerUpPredicate = function (mesh) {
  25882. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25883. };
  25884. }
  25885. // Meshes
  25886. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25887. _this._initActionManager(null, clickInfo);
  25888. }
  25889. if (!pickResult) {
  25890. pickResult = _this._currentPickResult;
  25891. }
  25892. _this._processPointerUp(pickResult, evt, clickInfo);
  25893. // Sprites
  25894. if (!clickInfo.ignore) {
  25895. if (_this.spriteManagers.length > 0) {
  25896. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25897. if (spritePickResult) {
  25898. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25899. if (spritePickResult.pickedSprite.actionManager) {
  25900. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25901. if (spritePickResult.pickedSprite.actionManager) {
  25902. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25903. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25904. }
  25905. }
  25906. }
  25907. }
  25908. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25909. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25910. }
  25911. }
  25912. }
  25913. }
  25914. _this._previousPickResult = _this._currentPickResult;
  25915. });
  25916. };
  25917. this._onKeyDown = function (evt) {
  25918. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25919. if (_this.onPreKeyboardObservable.hasObservers()) {
  25920. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25921. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25922. if (pi.skipOnPointerObservable) {
  25923. return;
  25924. }
  25925. }
  25926. if (_this.onKeyboardObservable.hasObservers()) {
  25927. var pi = new BABYLON.KeyboardInfo(type, evt);
  25928. _this.onKeyboardObservable.notifyObservers(pi, type);
  25929. }
  25930. if (_this.actionManager) {
  25931. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25932. }
  25933. };
  25934. this._onKeyUp = function (evt) {
  25935. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25936. if (_this.onPreKeyboardObservable.hasObservers()) {
  25937. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25938. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25939. if (pi.skipOnPointerObservable) {
  25940. return;
  25941. }
  25942. }
  25943. if (_this.onKeyboardObservable.hasObservers()) {
  25944. var pi = new BABYLON.KeyboardInfo(type, evt);
  25945. _this.onKeyboardObservable.notifyObservers(pi, type);
  25946. }
  25947. if (_this.actionManager) {
  25948. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25949. }
  25950. };
  25951. var engine = this.getEngine();
  25952. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25953. if (!canvas) {
  25954. return;
  25955. }
  25956. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25957. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25958. });
  25959. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25960. if (!canvas) {
  25961. return;
  25962. }
  25963. canvas.removeEventListener("keydown", _this._onKeyDown);
  25964. canvas.removeEventListener("keyup", _this._onKeyUp);
  25965. });
  25966. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25967. var canvas = this._engine.getRenderingCanvas();
  25968. if (!canvas) {
  25969. return;
  25970. }
  25971. if (attachMove) {
  25972. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25973. // Wheel
  25974. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25975. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25976. }
  25977. if (attachDown) {
  25978. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25979. }
  25980. if (attachUp) {
  25981. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25982. }
  25983. canvas.tabIndex = 1;
  25984. };
  25985. /** Detaches all event handlers*/
  25986. Scene.prototype.detachControl = function () {
  25987. var engine = this.getEngine();
  25988. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25989. var canvas = engine.getRenderingCanvas();
  25990. if (!canvas) {
  25991. return;
  25992. }
  25993. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25994. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25995. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25996. if (this._onCanvasBlurObserver) {
  25997. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25998. }
  25999. if (this._onCanvasFocusObserver) {
  26000. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26001. }
  26002. // Wheel
  26003. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26004. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26005. // Keyboard
  26006. canvas.removeEventListener("keydown", this._onKeyDown);
  26007. canvas.removeEventListener("keyup", this._onKeyUp);
  26008. // Observables
  26009. this.onKeyboardObservable.clear();
  26010. this.onPreKeyboardObservable.clear();
  26011. this.onPointerObservable.clear();
  26012. this.onPrePointerObservable.clear();
  26013. };
  26014. /**
  26015. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26016. * Delay loaded resources are not taking in account
  26017. * @return true if all required resources are ready
  26018. */
  26019. Scene.prototype.isReady = function () {
  26020. if (this._isDisposed) {
  26021. return false;
  26022. }
  26023. if (this._pendingData.length > 0) {
  26024. return false;
  26025. }
  26026. var index;
  26027. var engine = this.getEngine();
  26028. // Geometries
  26029. for (index = 0; index < this.geometries.length; index++) {
  26030. var geometry = this.geometries[index];
  26031. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26032. return false;
  26033. }
  26034. }
  26035. // Meshes
  26036. for (index = 0; index < this.meshes.length; index++) {
  26037. var mesh = this.meshes[index];
  26038. if (!mesh.isEnabled()) {
  26039. continue;
  26040. }
  26041. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26042. continue;
  26043. }
  26044. if (!mesh.isReady(true)) {
  26045. return false;
  26046. }
  26047. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26048. // Is Ready For Mesh
  26049. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26050. var step = _a[_i];
  26051. if (!step.action(mesh, hardwareInstancedRendering)) {
  26052. return false;
  26053. }
  26054. }
  26055. }
  26056. // Post-processes
  26057. if (this.activeCameras && this.activeCameras.length > 0) {
  26058. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26059. var camera = _c[_b];
  26060. if (!camera.isReady(true)) {
  26061. return false;
  26062. }
  26063. }
  26064. }
  26065. else if (this.activeCamera) {
  26066. if (!this.activeCamera.isReady(true)) {
  26067. return false;
  26068. }
  26069. }
  26070. // Particles
  26071. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26072. var particleSystem = _e[_d];
  26073. if (!particleSystem.isReady()) {
  26074. return false;
  26075. }
  26076. }
  26077. return true;
  26078. };
  26079. /** Resets all cached information relative to material (including effect and visibility) */
  26080. Scene.prototype.resetCachedMaterial = function () {
  26081. this._cachedMaterial = null;
  26082. this._cachedEffect = null;
  26083. this._cachedVisibility = null;
  26084. };
  26085. /**
  26086. * Registers a function to be called before every frame render
  26087. * @param func defines the function to register
  26088. */
  26089. Scene.prototype.registerBeforeRender = function (func) {
  26090. this.onBeforeRenderObservable.add(func);
  26091. };
  26092. /**
  26093. * Unregisters a function called before every frame render
  26094. * @param func defines the function to unregister
  26095. */
  26096. Scene.prototype.unregisterBeforeRender = function (func) {
  26097. this.onBeforeRenderObservable.removeCallback(func);
  26098. };
  26099. /**
  26100. * Registers a function to be called after every frame render
  26101. * @param func defines the function to register
  26102. */
  26103. Scene.prototype.registerAfterRender = function (func) {
  26104. this.onAfterRenderObservable.add(func);
  26105. };
  26106. /**
  26107. * Unregisters a function called after every frame render
  26108. * @param func defines the function to unregister
  26109. */
  26110. Scene.prototype.unregisterAfterRender = function (func) {
  26111. this.onAfterRenderObservable.removeCallback(func);
  26112. };
  26113. Scene.prototype._executeOnceBeforeRender = function (func) {
  26114. var _this = this;
  26115. var execFunc = function () {
  26116. func();
  26117. setTimeout(function () {
  26118. _this.unregisterBeforeRender(execFunc);
  26119. });
  26120. };
  26121. this.registerBeforeRender(execFunc);
  26122. };
  26123. /**
  26124. * The provided function will run before render once and will be disposed afterwards.
  26125. * A timeout delay can be provided so that the function will be executed in N ms.
  26126. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26127. * @param func The function to be executed.
  26128. * @param timeout optional delay in ms
  26129. */
  26130. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26131. var _this = this;
  26132. if (timeout !== undefined) {
  26133. setTimeout(function () {
  26134. _this._executeOnceBeforeRender(func);
  26135. }, timeout);
  26136. }
  26137. else {
  26138. this._executeOnceBeforeRender(func);
  26139. }
  26140. };
  26141. /** @hidden */
  26142. Scene.prototype._addPendingData = function (data) {
  26143. this._pendingData.push(data);
  26144. };
  26145. /** @hidden */
  26146. Scene.prototype._removePendingData = function (data) {
  26147. var wasLoading = this.isLoading;
  26148. var index = this._pendingData.indexOf(data);
  26149. if (index !== -1) {
  26150. this._pendingData.splice(index, 1);
  26151. }
  26152. if (wasLoading && !this.isLoading) {
  26153. this.onDataLoadedObservable.notifyObservers(this);
  26154. }
  26155. };
  26156. /**
  26157. * Returns the number of items waiting to be loaded
  26158. * @returns the number of items waiting to be loaded
  26159. */
  26160. Scene.prototype.getWaitingItemsCount = function () {
  26161. return this._pendingData.length;
  26162. };
  26163. Object.defineProperty(Scene.prototype, "isLoading", {
  26164. /**
  26165. * Returns a boolean indicating if the scene is still loading data
  26166. */
  26167. get: function () {
  26168. return this._pendingData.length > 0;
  26169. },
  26170. enumerable: true,
  26171. configurable: true
  26172. });
  26173. /**
  26174. * Registers a function to be executed when the scene is ready
  26175. * @param {Function} func - the function to be executed
  26176. */
  26177. Scene.prototype.executeWhenReady = function (func) {
  26178. var _this = this;
  26179. this.onReadyObservable.add(func);
  26180. if (this._executeWhenReadyTimeoutId !== -1) {
  26181. return;
  26182. }
  26183. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26184. _this._checkIsReady();
  26185. }, 150);
  26186. };
  26187. /**
  26188. * Returns a promise that resolves when the scene is ready
  26189. * @returns A promise that resolves when the scene is ready
  26190. */
  26191. Scene.prototype.whenReadyAsync = function () {
  26192. var _this = this;
  26193. return new Promise(function (resolve) {
  26194. _this.executeWhenReady(function () {
  26195. resolve();
  26196. });
  26197. });
  26198. };
  26199. /** @hidden */
  26200. Scene.prototype._checkIsReady = function () {
  26201. var _this = this;
  26202. this._registerTransientComponents();
  26203. if (this.isReady()) {
  26204. this.onReadyObservable.notifyObservers(this);
  26205. this.onReadyObservable.clear();
  26206. this._executeWhenReadyTimeoutId = -1;
  26207. return;
  26208. }
  26209. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26210. _this._checkIsReady();
  26211. }, 150);
  26212. };
  26213. // Animations
  26214. /**
  26215. * Will start the animation sequence of a given target
  26216. * @param target defines the target
  26217. * @param from defines from which frame should animation start
  26218. * @param to defines until which frame should animation run.
  26219. * @param weight defines the weight to apply to the animation (1.0 by default)
  26220. * @param loop defines if the animation loops
  26221. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26222. * @param onAnimationEnd defines the function to be executed when the animation ends
  26223. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26224. * @returns the animatable object created for this animation
  26225. */
  26226. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26227. if (weight === void 0) { weight = 1.0; }
  26228. if (speedRatio === void 0) { speedRatio = 1.0; }
  26229. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26230. returnedAnimatable.weight = weight;
  26231. return returnedAnimatable;
  26232. };
  26233. /**
  26234. * Will start the animation sequence of a given target
  26235. * @param target defines the target
  26236. * @param from defines from which frame should animation start
  26237. * @param to defines until which frame should animation run.
  26238. * @param loop defines if the animation loops
  26239. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26240. * @param onAnimationEnd defines the function to be executed when the animation ends
  26241. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26242. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26243. * @returns the animatable object created for this animation
  26244. */
  26245. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26246. if (speedRatio === void 0) { speedRatio = 1.0; }
  26247. if (stopCurrent === void 0) { stopCurrent = true; }
  26248. if (from > to && speedRatio > 0) {
  26249. speedRatio *= -1;
  26250. }
  26251. if (stopCurrent) {
  26252. this.stopAnimation(target);
  26253. }
  26254. if (!animatable) {
  26255. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26256. }
  26257. // Local animations
  26258. if (target.animations) {
  26259. animatable.appendAnimations(target, target.animations);
  26260. }
  26261. // Children animations
  26262. if (target.getAnimatables) {
  26263. var animatables = target.getAnimatables();
  26264. for (var index = 0; index < animatables.length; index++) {
  26265. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26266. }
  26267. }
  26268. animatable.reset();
  26269. return animatable;
  26270. };
  26271. /**
  26272. * Begin a new animation on a given node
  26273. * @param target defines the target where the animation will take place
  26274. * @param animations defines the list of animations to start
  26275. * @param from defines the initial value
  26276. * @param to defines the final value
  26277. * @param loop defines if you want animation to loop (off by default)
  26278. * @param speedRatio defines the speed ratio to apply to all animations
  26279. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26280. * @returns the list of created animatables
  26281. */
  26282. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26283. if (speedRatio === undefined) {
  26284. speedRatio = 1.0;
  26285. }
  26286. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26287. return animatable;
  26288. };
  26289. /**
  26290. * Begin a new animation on a given node and its hierarchy
  26291. * @param target defines the root node where the animation will take place
  26292. * @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.
  26293. * @param animations defines the list of animations to start
  26294. * @param from defines the initial value
  26295. * @param to defines the final value
  26296. * @param loop defines if you want animation to loop (off by default)
  26297. * @param speedRatio defines the speed ratio to apply to all animations
  26298. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26299. * @returns the list of animatables created for all nodes
  26300. */
  26301. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26302. var children = target.getDescendants(directDescendantsOnly);
  26303. var result = [];
  26304. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26305. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26306. var child = children_1[_i];
  26307. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26308. }
  26309. return result;
  26310. };
  26311. /**
  26312. * Gets the animatable associated with a specific target
  26313. * @param target defines the target of the animatable
  26314. * @returns the required animatable if found
  26315. */
  26316. Scene.prototype.getAnimatableByTarget = function (target) {
  26317. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26318. if (this._activeAnimatables[index].target === target) {
  26319. return this._activeAnimatables[index];
  26320. }
  26321. }
  26322. return null;
  26323. };
  26324. /**
  26325. * Gets all animatables associated with a given target
  26326. * @param target defines the target to look animatables for
  26327. * @returns an array of Animatables
  26328. */
  26329. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26330. var result = [];
  26331. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26332. if (this._activeAnimatables[index].target === target) {
  26333. result.push(this._activeAnimatables[index]);
  26334. }
  26335. }
  26336. return result;
  26337. };
  26338. Object.defineProperty(Scene.prototype, "animatables", {
  26339. /**
  26340. * Gets all animatable attached to the scene
  26341. */
  26342. get: function () {
  26343. return this._activeAnimatables;
  26344. },
  26345. enumerable: true,
  26346. configurable: true
  26347. });
  26348. /**
  26349. * Will stop the animation of the given target
  26350. * @param target - the target
  26351. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26352. */
  26353. Scene.prototype.stopAnimation = function (target, animationName) {
  26354. var animatables = this.getAllAnimatablesByTarget(target);
  26355. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26356. var animatable = animatables_1[_i];
  26357. animatable.stop(animationName);
  26358. }
  26359. };
  26360. /**
  26361. * Stops and removes all animations that have been applied to the scene
  26362. */
  26363. Scene.prototype.stopAllAnimations = function () {
  26364. if (this._activeAnimatables) {
  26365. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26366. this._activeAnimatables[i].stop();
  26367. }
  26368. this._activeAnimatables = [];
  26369. }
  26370. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26371. var group = _a[_i];
  26372. group.stop();
  26373. }
  26374. };
  26375. Scene.prototype._animate = function () {
  26376. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26377. return;
  26378. }
  26379. // Getting time
  26380. var now = BABYLON.Tools.Now;
  26381. if (!this._animationTimeLast) {
  26382. if (this._pendingData.length > 0) {
  26383. return;
  26384. }
  26385. this._animationTimeLast = now;
  26386. }
  26387. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26388. this._animationTime += deltaTime;
  26389. this._animationTimeLast = now;
  26390. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26391. this._activeAnimatables[index]._animate(this._animationTime);
  26392. }
  26393. // Late animation bindings
  26394. this._processLateAnimationBindings();
  26395. };
  26396. /** @hidden */
  26397. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26398. var target = runtimeAnimation.target;
  26399. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26400. if (!target._lateAnimationHolders) {
  26401. target._lateAnimationHolders = {};
  26402. }
  26403. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26404. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26405. totalWeight: 0,
  26406. animations: [],
  26407. originalValue: originalValue
  26408. };
  26409. }
  26410. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26411. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26412. };
  26413. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26414. var normalizer = 1.0;
  26415. var finalPosition = BABYLON.Tmp.Vector3[0];
  26416. var finalScaling = BABYLON.Tmp.Vector3[1];
  26417. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26418. var startIndex = 0;
  26419. var originalAnimation = holder.animations[0];
  26420. var originalValue = holder.originalValue;
  26421. var scale = 1;
  26422. if (holder.totalWeight < 1.0) {
  26423. // We need to mix the original value in
  26424. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26425. scale = 1.0 - holder.totalWeight;
  26426. }
  26427. else {
  26428. startIndex = 1;
  26429. // We need to normalize the weights
  26430. normalizer = holder.totalWeight;
  26431. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26432. scale = originalAnimation.weight / normalizer;
  26433. if (scale == 1) {
  26434. return originalAnimation.currentValue;
  26435. }
  26436. }
  26437. finalScaling.scaleInPlace(scale);
  26438. finalPosition.scaleInPlace(scale);
  26439. finalQuaternion.scaleInPlace(scale);
  26440. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26441. var runtimeAnimation = holder.animations[animIndex];
  26442. var scale = runtimeAnimation.weight / normalizer;
  26443. var currentPosition = BABYLON.Tmp.Vector3[2];
  26444. var currentScaling = BABYLON.Tmp.Vector3[3];
  26445. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26446. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26447. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26448. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26449. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26450. }
  26451. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26452. return originalAnimation._workValue;
  26453. };
  26454. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26455. var originalAnimation = holder.animations[0];
  26456. var originalValue = holder.originalValue;
  26457. if (holder.animations.length === 1) {
  26458. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26459. }
  26460. var normalizer = 1.0;
  26461. var quaternions;
  26462. var weights;
  26463. if (holder.totalWeight < 1.0) {
  26464. var scale = 1.0 - holder.totalWeight;
  26465. quaternions = [];
  26466. weights = [];
  26467. quaternions.push(originalValue);
  26468. weights.push(scale);
  26469. }
  26470. else {
  26471. if (holder.animations.length === 2) { // Slerp as soon as we can
  26472. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26473. }
  26474. quaternions = [];
  26475. weights = [];
  26476. normalizer = holder.totalWeight;
  26477. }
  26478. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26479. var runtimeAnimation = holder.animations[animIndex];
  26480. quaternions.push(runtimeAnimation.currentValue);
  26481. weights.push(runtimeAnimation.weight / normalizer);
  26482. }
  26483. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26484. var cumulativeAmount = 0;
  26485. var cumulativeQuaternion = null;
  26486. for (var index = 0; index < quaternions.length;) {
  26487. if (!cumulativeQuaternion) {
  26488. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26489. cumulativeAmount = weights[index] + weights[index + 1];
  26490. index += 2;
  26491. continue;
  26492. }
  26493. cumulativeAmount += weights[index];
  26494. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26495. index++;
  26496. }
  26497. return cumulativeQuaternion;
  26498. };
  26499. Scene.prototype._processLateAnimationBindings = function () {
  26500. if (!this._registeredForLateAnimationBindings.length) {
  26501. return;
  26502. }
  26503. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26504. var target = this._registeredForLateAnimationBindings.data[index];
  26505. for (var path in target._lateAnimationHolders) {
  26506. var holder = target._lateAnimationHolders[path];
  26507. var originalAnimation = holder.animations[0];
  26508. var originalValue = holder.originalValue;
  26509. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26510. var finalValue = void 0;
  26511. if (matrixDecomposeMode) {
  26512. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26513. }
  26514. else {
  26515. var quaternionMode = originalValue.w !== undefined;
  26516. if (quaternionMode) {
  26517. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26518. }
  26519. else {
  26520. var startIndex = 0;
  26521. var normalizer = 1.0;
  26522. if (holder.totalWeight < 1.0) {
  26523. // We need to mix the original value in
  26524. if (originalValue.scale) {
  26525. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26526. }
  26527. else {
  26528. finalValue = originalValue * (1.0 - holder.totalWeight);
  26529. }
  26530. }
  26531. else {
  26532. // We need to normalize the weights
  26533. normalizer = holder.totalWeight;
  26534. var scale_1 = originalAnimation.weight / normalizer;
  26535. if (scale_1 !== 1) {
  26536. if (originalAnimation.currentValue.scale) {
  26537. finalValue = originalAnimation.currentValue.scale(scale_1);
  26538. }
  26539. else {
  26540. finalValue = originalAnimation.currentValue * scale_1;
  26541. }
  26542. }
  26543. else {
  26544. finalValue = originalAnimation.currentValue;
  26545. }
  26546. startIndex = 1;
  26547. }
  26548. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26549. var runtimeAnimation = holder.animations[animIndex];
  26550. var scale = runtimeAnimation.weight / normalizer;
  26551. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26552. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26553. }
  26554. else {
  26555. finalValue += runtimeAnimation.currentValue * scale;
  26556. }
  26557. }
  26558. }
  26559. }
  26560. target[path] = finalValue;
  26561. }
  26562. target._lateAnimationHolders = {};
  26563. }
  26564. this._registeredForLateAnimationBindings.reset();
  26565. };
  26566. // Matrix
  26567. /** @hidden */
  26568. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26569. this._useAlternateCameraConfiguration = active;
  26570. };
  26571. /**
  26572. * Gets the current view matrix
  26573. * @returns a Matrix
  26574. */
  26575. Scene.prototype.getViewMatrix = function () {
  26576. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26577. };
  26578. /**
  26579. * Gets the current projection matrix
  26580. * @returns a Matrix
  26581. */
  26582. Scene.prototype.getProjectionMatrix = function () {
  26583. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26584. };
  26585. /**
  26586. * Gets the current transform matrix
  26587. * @returns a Matrix made of View * Projection
  26588. */
  26589. Scene.prototype.getTransformMatrix = function () {
  26590. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26591. };
  26592. /**
  26593. * Sets the current transform matrix
  26594. * @param view defines the View matrix to use
  26595. * @param projection defines the Projection matrix to use
  26596. */
  26597. Scene.prototype.setTransformMatrix = function (view, projection) {
  26598. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26599. return;
  26600. }
  26601. this._viewUpdateFlag = view.updateFlag;
  26602. this._projectionUpdateFlag = projection.updateFlag;
  26603. this._viewMatrix = view;
  26604. this._projectionMatrix = projection;
  26605. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26606. // Update frustum
  26607. if (!this._frustumPlanes) {
  26608. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26609. }
  26610. else {
  26611. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26612. }
  26613. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26614. var otherCamera = this.activeCamera._alternateCamera;
  26615. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26616. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26617. }
  26618. if (this._sceneUbo.useUbo) {
  26619. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26620. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26621. this._sceneUbo.update();
  26622. }
  26623. };
  26624. /** @hidden */
  26625. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26626. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26627. return;
  26628. }
  26629. this._alternateViewUpdateFlag = view.updateFlag;
  26630. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26631. this._alternateViewMatrix = view;
  26632. this._alternateProjectionMatrix = projection;
  26633. if (!this._alternateTransformMatrix) {
  26634. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26635. }
  26636. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26637. if (!this._alternateSceneUbo) {
  26638. this._createAlternateUbo();
  26639. }
  26640. if (this._alternateSceneUbo.useUbo) {
  26641. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26642. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26643. this._alternateSceneUbo.update();
  26644. }
  26645. };
  26646. /**
  26647. * Gets the uniform buffer used to store scene data
  26648. * @returns a UniformBuffer
  26649. */
  26650. Scene.prototype.getSceneUniformBuffer = function () {
  26651. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26652. };
  26653. /**
  26654. * Gets an unique (relatively to the current scene) Id
  26655. * @returns an unique number for the scene
  26656. */
  26657. Scene.prototype.getUniqueId = function () {
  26658. var result = Scene._uniqueIdCounter;
  26659. Scene._uniqueIdCounter++;
  26660. return result;
  26661. };
  26662. /**
  26663. * Add a mesh to the list of scene's meshes
  26664. * @param newMesh defines the mesh to add
  26665. * @param recursive if all child meshes should also be added to the scene
  26666. */
  26667. Scene.prototype.addMesh = function (newMesh, recursive) {
  26668. var _this = this;
  26669. if (recursive === void 0) { recursive = false; }
  26670. this.meshes.push(newMesh);
  26671. //notify the collision coordinator
  26672. if (this.collisionCoordinator) {
  26673. this.collisionCoordinator.onMeshAdded(newMesh);
  26674. }
  26675. newMesh._resyncLightSources();
  26676. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26677. if (recursive) {
  26678. newMesh.getChildMeshes().forEach(function (m) {
  26679. _this.addMesh(m);
  26680. });
  26681. }
  26682. };
  26683. /**
  26684. * Remove a mesh for the list of scene's meshes
  26685. * @param toRemove defines the mesh to remove
  26686. * @param recursive if all child meshes should also be removed from the scene
  26687. * @returns the index where the mesh was in the mesh list
  26688. */
  26689. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26690. var _this = this;
  26691. if (recursive === void 0) { recursive = false; }
  26692. var index = this.meshes.indexOf(toRemove);
  26693. if (index !== -1) {
  26694. // Remove from the scene if mesh found
  26695. this.meshes.splice(index, 1);
  26696. }
  26697. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26698. if (recursive) {
  26699. toRemove.getChildMeshes().forEach(function (m) {
  26700. _this.removeMesh(m);
  26701. });
  26702. }
  26703. return index;
  26704. };
  26705. /**
  26706. * Add a transform node to the list of scene's transform nodes
  26707. * @param newTransformNode defines the transform node to add
  26708. */
  26709. Scene.prototype.addTransformNode = function (newTransformNode) {
  26710. this.transformNodes.push(newTransformNode);
  26711. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26712. };
  26713. /**
  26714. * Remove a transform node for the list of scene's transform nodes
  26715. * @param toRemove defines the transform node to remove
  26716. * @returns the index where the transform node was in the transform node list
  26717. */
  26718. Scene.prototype.removeTransformNode = function (toRemove) {
  26719. var index = this.transformNodes.indexOf(toRemove);
  26720. if (index !== -1) {
  26721. // Remove from the scene if found
  26722. this.transformNodes.splice(index, 1);
  26723. }
  26724. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26725. return index;
  26726. };
  26727. /**
  26728. * Remove a skeleton for the list of scene's skeletons
  26729. * @param toRemove defines the skeleton to remove
  26730. * @returns the index where the skeleton was in the skeleton list
  26731. */
  26732. Scene.prototype.removeSkeleton = function (toRemove) {
  26733. var index = this.skeletons.indexOf(toRemove);
  26734. if (index !== -1) {
  26735. // Remove from the scene if found
  26736. this.skeletons.splice(index, 1);
  26737. }
  26738. return index;
  26739. };
  26740. /**
  26741. * Remove a morph target for the list of scene's morph targets
  26742. * @param toRemove defines the morph target to remove
  26743. * @returns the index where the morph target was in the morph target list
  26744. */
  26745. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26746. var index = this.morphTargetManagers.indexOf(toRemove);
  26747. if (index !== -1) {
  26748. // Remove from the scene if found
  26749. this.morphTargetManagers.splice(index, 1);
  26750. }
  26751. return index;
  26752. };
  26753. /**
  26754. * Remove a light for the list of scene's lights
  26755. * @param toRemove defines the light to remove
  26756. * @returns the index where the light was in the light list
  26757. */
  26758. Scene.prototype.removeLight = function (toRemove) {
  26759. var index = this.lights.indexOf(toRemove);
  26760. if (index !== -1) {
  26761. // Remove from meshes
  26762. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26763. var mesh = _a[_i];
  26764. mesh._removeLightSource(toRemove);
  26765. }
  26766. // Remove from the scene if mesh found
  26767. this.lights.splice(index, 1);
  26768. this.sortLightsByPriority();
  26769. }
  26770. this.onLightRemovedObservable.notifyObservers(toRemove);
  26771. return index;
  26772. };
  26773. /**
  26774. * Remove a camera for the list of scene's cameras
  26775. * @param toRemove defines the camera to remove
  26776. * @returns the index where the camera was in the camera list
  26777. */
  26778. Scene.prototype.removeCamera = function (toRemove) {
  26779. var index = this.cameras.indexOf(toRemove);
  26780. if (index !== -1) {
  26781. // Remove from the scene if mesh found
  26782. this.cameras.splice(index, 1);
  26783. }
  26784. // Remove from activeCameras
  26785. var index2 = this.activeCameras.indexOf(toRemove);
  26786. if (index2 !== -1) {
  26787. // Remove from the scene if mesh found
  26788. this.activeCameras.splice(index2, 1);
  26789. }
  26790. // Reset the activeCamera
  26791. if (this.activeCamera === toRemove) {
  26792. if (this.cameras.length > 0) {
  26793. this.activeCamera = this.cameras[0];
  26794. }
  26795. else {
  26796. this.activeCamera = null;
  26797. }
  26798. }
  26799. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26800. return index;
  26801. };
  26802. /**
  26803. * Remove a particle system for the list of scene's particle systems
  26804. * @param toRemove defines the particle system to remove
  26805. * @returns the index where the particle system was in the particle system list
  26806. */
  26807. Scene.prototype.removeParticleSystem = function (toRemove) {
  26808. var index = this.particleSystems.indexOf(toRemove);
  26809. if (index !== -1) {
  26810. this.particleSystems.splice(index, 1);
  26811. }
  26812. return index;
  26813. };
  26814. /**
  26815. * Remove a animation for the list of scene's animations
  26816. * @param toRemove defines the animation to remove
  26817. * @returns the index where the animation was in the animation list
  26818. */
  26819. Scene.prototype.removeAnimation = function (toRemove) {
  26820. var index = this.animations.indexOf(toRemove);
  26821. if (index !== -1) {
  26822. this.animations.splice(index, 1);
  26823. }
  26824. return index;
  26825. };
  26826. /**
  26827. * Removes the given animation group from this scene.
  26828. * @param toRemove The animation group to remove
  26829. * @returns The index of the removed animation group
  26830. */
  26831. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26832. var index = this.animationGroups.indexOf(toRemove);
  26833. if (index !== -1) {
  26834. this.animationGroups.splice(index, 1);
  26835. }
  26836. return index;
  26837. };
  26838. /**
  26839. * Removes the given multi-material from this scene.
  26840. * @param toRemove The multi-material to remove
  26841. * @returns The index of the removed multi-material
  26842. */
  26843. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26844. var index = this.multiMaterials.indexOf(toRemove);
  26845. if (index !== -1) {
  26846. this.multiMaterials.splice(index, 1);
  26847. }
  26848. return index;
  26849. };
  26850. /**
  26851. * Removes the given material from this scene.
  26852. * @param toRemove The material to remove
  26853. * @returns The index of the removed material
  26854. */
  26855. Scene.prototype.removeMaterial = function (toRemove) {
  26856. var index = this.materials.indexOf(toRemove);
  26857. if (index !== -1) {
  26858. this.materials.splice(index, 1);
  26859. }
  26860. return index;
  26861. };
  26862. /**
  26863. * Removes the given action manager from this scene.
  26864. * @param toRemove The action manager to remove
  26865. * @returns The index of the removed action manager
  26866. */
  26867. Scene.prototype.removeActionManager = function (toRemove) {
  26868. var index = this.actionManagers.indexOf(toRemove);
  26869. if (index !== -1) {
  26870. this.actionManagers.splice(index, 1);
  26871. }
  26872. return index;
  26873. };
  26874. /**
  26875. * Removes the given texture from this scene.
  26876. * @param toRemove The texture to remove
  26877. * @returns The index of the removed texture
  26878. */
  26879. Scene.prototype.removeTexture = function (toRemove) {
  26880. var index = this.textures.indexOf(toRemove);
  26881. if (index !== -1) {
  26882. this.textures.splice(index, 1);
  26883. }
  26884. return index;
  26885. };
  26886. /**
  26887. * Adds the given light to this scene
  26888. * @param newLight The light to add
  26889. */
  26890. Scene.prototype.addLight = function (newLight) {
  26891. this.lights.push(newLight);
  26892. this.sortLightsByPriority();
  26893. // Add light to all meshes (To support if the light is removed and then readded)
  26894. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26895. var mesh = _a[_i];
  26896. if (mesh._lightSources.indexOf(newLight) === -1) {
  26897. mesh._lightSources.push(newLight);
  26898. mesh._resyncLightSources();
  26899. }
  26900. }
  26901. this.onNewLightAddedObservable.notifyObservers(newLight);
  26902. };
  26903. /**
  26904. * Sorts the list list based on light priorities
  26905. */
  26906. Scene.prototype.sortLightsByPriority = function () {
  26907. if (this.requireLightSorting) {
  26908. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26909. }
  26910. };
  26911. /**
  26912. * Adds the given camera to this scene
  26913. * @param newCamera The camera to add
  26914. */
  26915. Scene.prototype.addCamera = function (newCamera) {
  26916. this.cameras.push(newCamera);
  26917. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26918. };
  26919. /**
  26920. * Adds the given skeleton to this scene
  26921. * @param newSkeleton The skeleton to add
  26922. */
  26923. Scene.prototype.addSkeleton = function (newSkeleton) {
  26924. this.skeletons.push(newSkeleton);
  26925. };
  26926. /**
  26927. * Adds the given particle system to this scene
  26928. * @param newParticleSystem The particle system to add
  26929. */
  26930. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26931. this.particleSystems.push(newParticleSystem);
  26932. };
  26933. /**
  26934. * Adds the given animation to this scene
  26935. * @param newAnimation The animation to add
  26936. */
  26937. Scene.prototype.addAnimation = function (newAnimation) {
  26938. this.animations.push(newAnimation);
  26939. };
  26940. /**
  26941. * Adds the given animation group to this scene.
  26942. * @param newAnimationGroup The animation group to add
  26943. */
  26944. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26945. this.animationGroups.push(newAnimationGroup);
  26946. };
  26947. /**
  26948. * Adds the given multi-material to this scene
  26949. * @param newMultiMaterial The multi-material to add
  26950. */
  26951. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26952. this.multiMaterials.push(newMultiMaterial);
  26953. };
  26954. /**
  26955. * Adds the given material to this scene
  26956. * @param newMaterial The material to add
  26957. */
  26958. Scene.prototype.addMaterial = function (newMaterial) {
  26959. this.materials.push(newMaterial);
  26960. };
  26961. /**
  26962. * Adds the given morph target to this scene
  26963. * @param newMorphTargetManager The morph target to add
  26964. */
  26965. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26966. this.morphTargetManagers.push(newMorphTargetManager);
  26967. };
  26968. /**
  26969. * Adds the given geometry to this scene
  26970. * @param newGeometry The geometry to add
  26971. */
  26972. Scene.prototype.addGeometry = function (newGeometry) {
  26973. this.geometries.push(newGeometry);
  26974. };
  26975. /**
  26976. * Adds the given action manager to this scene
  26977. * @param newActionManager The action manager to add
  26978. */
  26979. Scene.prototype.addActionManager = function (newActionManager) {
  26980. this.actionManagers.push(newActionManager);
  26981. };
  26982. /**
  26983. * Adds the given texture to this scene.
  26984. * @param newTexture The texture to add
  26985. */
  26986. Scene.prototype.addTexture = function (newTexture) {
  26987. this.textures.push(newTexture);
  26988. };
  26989. /**
  26990. * Switch active camera
  26991. * @param newCamera defines the new active camera
  26992. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26993. */
  26994. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26995. if (attachControl === void 0) { attachControl = true; }
  26996. var canvas = this._engine.getRenderingCanvas();
  26997. if (!canvas) {
  26998. return;
  26999. }
  27000. if (this.activeCamera) {
  27001. this.activeCamera.detachControl(canvas);
  27002. }
  27003. this.activeCamera = newCamera;
  27004. if (attachControl) {
  27005. newCamera.attachControl(canvas);
  27006. }
  27007. };
  27008. /**
  27009. * sets the active camera of the scene using its ID
  27010. * @param id defines the camera's ID
  27011. * @return the new active camera or null if none found.
  27012. */
  27013. Scene.prototype.setActiveCameraByID = function (id) {
  27014. var camera = this.getCameraByID(id);
  27015. if (camera) {
  27016. this.activeCamera = camera;
  27017. return camera;
  27018. }
  27019. return null;
  27020. };
  27021. /**
  27022. * sets the active camera of the scene using its name
  27023. * @param name defines the camera's name
  27024. * @returns the new active camera or null if none found.
  27025. */
  27026. Scene.prototype.setActiveCameraByName = function (name) {
  27027. var camera = this.getCameraByName(name);
  27028. if (camera) {
  27029. this.activeCamera = camera;
  27030. return camera;
  27031. }
  27032. return null;
  27033. };
  27034. /**
  27035. * get an animation group using its name
  27036. * @param name defines the material's name
  27037. * @return the animation group or null if none found.
  27038. */
  27039. Scene.prototype.getAnimationGroupByName = function (name) {
  27040. for (var index = 0; index < this.animationGroups.length; index++) {
  27041. if (this.animationGroups[index].name === name) {
  27042. return this.animationGroups[index];
  27043. }
  27044. }
  27045. return null;
  27046. };
  27047. /**
  27048. * get a material using its id
  27049. * @param id defines the material's ID
  27050. * @return the material or null if none found.
  27051. */
  27052. Scene.prototype.getMaterialByID = function (id) {
  27053. for (var index = 0; index < this.materials.length; index++) {
  27054. if (this.materials[index].id === id) {
  27055. return this.materials[index];
  27056. }
  27057. }
  27058. return null;
  27059. };
  27060. /**
  27061. * Gets a material using its name
  27062. * @param name defines the material's name
  27063. * @return the material or null if none found.
  27064. */
  27065. Scene.prototype.getMaterialByName = function (name) {
  27066. for (var index = 0; index < this.materials.length; index++) {
  27067. if (this.materials[index].name === name) {
  27068. return this.materials[index];
  27069. }
  27070. }
  27071. return null;
  27072. };
  27073. /**
  27074. * Gets a camera using its id
  27075. * @param id defines the id to look for
  27076. * @returns the camera or null if not found
  27077. */
  27078. Scene.prototype.getCameraByID = function (id) {
  27079. for (var index = 0; index < this.cameras.length; index++) {
  27080. if (this.cameras[index].id === id) {
  27081. return this.cameras[index];
  27082. }
  27083. }
  27084. return null;
  27085. };
  27086. /**
  27087. * Gets a camera using its unique id
  27088. * @param uniqueId defines the unique id to look for
  27089. * @returns the camera or null if not found
  27090. */
  27091. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27092. for (var index = 0; index < this.cameras.length; index++) {
  27093. if (this.cameras[index].uniqueId === uniqueId) {
  27094. return this.cameras[index];
  27095. }
  27096. }
  27097. return null;
  27098. };
  27099. /**
  27100. * Gets a camera using its name
  27101. * @param name defines the camera's name
  27102. * @return the camera or null if none found.
  27103. */
  27104. Scene.prototype.getCameraByName = function (name) {
  27105. for (var index = 0; index < this.cameras.length; index++) {
  27106. if (this.cameras[index].name === name) {
  27107. return this.cameras[index];
  27108. }
  27109. }
  27110. return null;
  27111. };
  27112. /**
  27113. * Gets a bone using its id
  27114. * @param id defines the bone's id
  27115. * @return the bone or null if not found
  27116. */
  27117. Scene.prototype.getBoneByID = function (id) {
  27118. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27119. var skeleton = this.skeletons[skeletonIndex];
  27120. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27121. if (skeleton.bones[boneIndex].id === id) {
  27122. return skeleton.bones[boneIndex];
  27123. }
  27124. }
  27125. }
  27126. return null;
  27127. };
  27128. /**
  27129. * Gets a bone using its id
  27130. * @param name defines the bone's name
  27131. * @return the bone or null if not found
  27132. */
  27133. Scene.prototype.getBoneByName = function (name) {
  27134. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27135. var skeleton = this.skeletons[skeletonIndex];
  27136. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27137. if (skeleton.bones[boneIndex].name === name) {
  27138. return skeleton.bones[boneIndex];
  27139. }
  27140. }
  27141. }
  27142. return null;
  27143. };
  27144. /**
  27145. * Gets a light node using its name
  27146. * @param name defines the the light's name
  27147. * @return the light or null if none found.
  27148. */
  27149. Scene.prototype.getLightByName = function (name) {
  27150. for (var index = 0; index < this.lights.length; index++) {
  27151. if (this.lights[index].name === name) {
  27152. return this.lights[index];
  27153. }
  27154. }
  27155. return null;
  27156. };
  27157. /**
  27158. * Gets a light node using its id
  27159. * @param id defines the light's id
  27160. * @return the light or null if none found.
  27161. */
  27162. Scene.prototype.getLightByID = function (id) {
  27163. for (var index = 0; index < this.lights.length; index++) {
  27164. if (this.lights[index].id === id) {
  27165. return this.lights[index];
  27166. }
  27167. }
  27168. return null;
  27169. };
  27170. /**
  27171. * Gets a light node using its scene-generated unique ID
  27172. * @param uniqueId defines the light's unique id
  27173. * @return the light or null if none found.
  27174. */
  27175. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27176. for (var index = 0; index < this.lights.length; index++) {
  27177. if (this.lights[index].uniqueId === uniqueId) {
  27178. return this.lights[index];
  27179. }
  27180. }
  27181. return null;
  27182. };
  27183. /**
  27184. * Gets a particle system by id
  27185. * @param id defines the particle system id
  27186. * @return the corresponding system or null if none found
  27187. */
  27188. Scene.prototype.getParticleSystemByID = function (id) {
  27189. for (var index = 0; index < this.particleSystems.length; index++) {
  27190. if (this.particleSystems[index].id === id) {
  27191. return this.particleSystems[index];
  27192. }
  27193. }
  27194. return null;
  27195. };
  27196. /**
  27197. * Gets a geometry using its ID
  27198. * @param id defines the geometry's id
  27199. * @return the geometry or null if none found.
  27200. */
  27201. Scene.prototype.getGeometryByID = function (id) {
  27202. for (var index = 0; index < this.geometries.length; index++) {
  27203. if (this.geometries[index].id === id) {
  27204. return this.geometries[index];
  27205. }
  27206. }
  27207. return null;
  27208. };
  27209. /**
  27210. * Add a new geometry to this scene
  27211. * @param geometry defines the geometry to be added to the scene.
  27212. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27213. * @return a boolean defining if the geometry was added or not
  27214. */
  27215. Scene.prototype.pushGeometry = function (geometry, force) {
  27216. if (!force && this.getGeometryByID(geometry.id)) {
  27217. return false;
  27218. }
  27219. this.geometries.push(geometry);
  27220. //notify the collision coordinator
  27221. if (this.collisionCoordinator) {
  27222. this.collisionCoordinator.onGeometryAdded(geometry);
  27223. }
  27224. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27225. return true;
  27226. };
  27227. /**
  27228. * Removes an existing geometry
  27229. * @param geometry defines the geometry to be removed from the scene
  27230. * @return a boolean defining if the geometry was removed or not
  27231. */
  27232. Scene.prototype.removeGeometry = function (geometry) {
  27233. var index = this.geometries.indexOf(geometry);
  27234. if (index > -1) {
  27235. this.geometries.splice(index, 1);
  27236. //notify the collision coordinator
  27237. if (this.collisionCoordinator) {
  27238. this.collisionCoordinator.onGeometryDeleted(geometry);
  27239. }
  27240. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27241. return true;
  27242. }
  27243. return false;
  27244. };
  27245. /**
  27246. * Gets the list of geometries attached to the scene
  27247. * @returns an array of Geometry
  27248. */
  27249. Scene.prototype.getGeometries = function () {
  27250. return this.geometries;
  27251. };
  27252. /**
  27253. * Gets the first added mesh found of a given ID
  27254. * @param id defines the id to search for
  27255. * @return the mesh found or null if not found at all
  27256. */
  27257. Scene.prototype.getMeshByID = function (id) {
  27258. for (var index = 0; index < this.meshes.length; index++) {
  27259. if (this.meshes[index].id === id) {
  27260. return this.meshes[index];
  27261. }
  27262. }
  27263. return null;
  27264. };
  27265. /**
  27266. * Gets a list of meshes using their id
  27267. * @param id defines the id to search for
  27268. * @returns a list of meshes
  27269. */
  27270. Scene.prototype.getMeshesByID = function (id) {
  27271. return this.meshes.filter(function (m) {
  27272. return m.id === id;
  27273. });
  27274. };
  27275. /**
  27276. * Gets the first added transform node found of a given ID
  27277. * @param id defines the id to search for
  27278. * @return the found transform node or null if not found at all.
  27279. */
  27280. Scene.prototype.getTransformNodeByID = function (id) {
  27281. for (var index = 0; index < this.transformNodes.length; index++) {
  27282. if (this.transformNodes[index].id === id) {
  27283. return this.transformNodes[index];
  27284. }
  27285. }
  27286. return null;
  27287. };
  27288. /**
  27289. * Gets a list of transform nodes using their id
  27290. * @param id defines the id to search for
  27291. * @returns a list of transform nodes
  27292. */
  27293. Scene.prototype.getTransformNodesByID = function (id) {
  27294. return this.transformNodes.filter(function (m) {
  27295. return m.id === id;
  27296. });
  27297. };
  27298. /**
  27299. * Gets a mesh with its auto-generated unique id
  27300. * @param uniqueId defines the unique id to search for
  27301. * @return the found mesh or null if not found at all.
  27302. */
  27303. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27304. for (var index = 0; index < this.meshes.length; index++) {
  27305. if (this.meshes[index].uniqueId === uniqueId) {
  27306. return this.meshes[index];
  27307. }
  27308. }
  27309. return null;
  27310. };
  27311. /**
  27312. * Gets a the last added mesh using a given id
  27313. * @param id defines the id to search for
  27314. * @return the found mesh or null if not found at all.
  27315. */
  27316. Scene.prototype.getLastMeshByID = function (id) {
  27317. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27318. if (this.meshes[index].id === id) {
  27319. return this.meshes[index];
  27320. }
  27321. }
  27322. return null;
  27323. };
  27324. /**
  27325. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27326. * @param id defines the id to search for
  27327. * @return the found node or null if not found at all
  27328. */
  27329. Scene.prototype.getLastEntryByID = function (id) {
  27330. var index;
  27331. for (index = this.meshes.length - 1; index >= 0; index--) {
  27332. if (this.meshes[index].id === id) {
  27333. return this.meshes[index];
  27334. }
  27335. }
  27336. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27337. if (this.transformNodes[index].id === id) {
  27338. return this.transformNodes[index];
  27339. }
  27340. }
  27341. for (index = this.cameras.length - 1; index >= 0; index--) {
  27342. if (this.cameras[index].id === id) {
  27343. return this.cameras[index];
  27344. }
  27345. }
  27346. for (index = this.lights.length - 1; index >= 0; index--) {
  27347. if (this.lights[index].id === id) {
  27348. return this.lights[index];
  27349. }
  27350. }
  27351. return null;
  27352. };
  27353. /**
  27354. * Gets a node (Mesh, Camera, Light) using a given id
  27355. * @param id defines the id to search for
  27356. * @return the found node or null if not found at all
  27357. */
  27358. Scene.prototype.getNodeByID = function (id) {
  27359. var mesh = this.getMeshByID(id);
  27360. if (mesh) {
  27361. return mesh;
  27362. }
  27363. var light = this.getLightByID(id);
  27364. if (light) {
  27365. return light;
  27366. }
  27367. var camera = this.getCameraByID(id);
  27368. if (camera) {
  27369. return camera;
  27370. }
  27371. var bone = this.getBoneByID(id);
  27372. return bone;
  27373. };
  27374. /**
  27375. * Gets a node (Mesh, Camera, Light) using a given name
  27376. * @param name defines the name to search for
  27377. * @return the found node or null if not found at all.
  27378. */
  27379. Scene.prototype.getNodeByName = function (name) {
  27380. var mesh = this.getMeshByName(name);
  27381. if (mesh) {
  27382. return mesh;
  27383. }
  27384. var light = this.getLightByName(name);
  27385. if (light) {
  27386. return light;
  27387. }
  27388. var camera = this.getCameraByName(name);
  27389. if (camera) {
  27390. return camera;
  27391. }
  27392. var bone = this.getBoneByName(name);
  27393. return bone;
  27394. };
  27395. /**
  27396. * Gets a mesh using a given name
  27397. * @param name defines the name to search for
  27398. * @return the found mesh or null if not found at all.
  27399. */
  27400. Scene.prototype.getMeshByName = function (name) {
  27401. for (var index = 0; index < this.meshes.length; index++) {
  27402. if (this.meshes[index].name === name) {
  27403. return this.meshes[index];
  27404. }
  27405. }
  27406. return null;
  27407. };
  27408. /**
  27409. * Gets a transform node using a given name
  27410. * @param name defines the name to search for
  27411. * @return the found transform node or null if not found at all.
  27412. */
  27413. Scene.prototype.getTransformNodeByName = function (name) {
  27414. for (var index = 0; index < this.transformNodes.length; index++) {
  27415. if (this.transformNodes[index].name === name) {
  27416. return this.transformNodes[index];
  27417. }
  27418. }
  27419. return null;
  27420. };
  27421. /**
  27422. * Gets a sound using a given name
  27423. * @param name defines the name to search for
  27424. * @return the found sound or null if not found at all.
  27425. */
  27426. Scene.prototype.getSoundByName = function (name) {
  27427. var index;
  27428. if (BABYLON.AudioEngine) {
  27429. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27430. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27431. return this.mainSoundTrack.soundCollection[index];
  27432. }
  27433. }
  27434. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27435. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27436. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27437. return this.soundTracks[sdIndex].soundCollection[index];
  27438. }
  27439. }
  27440. }
  27441. }
  27442. return null;
  27443. };
  27444. /**
  27445. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27446. * @param id defines the id to search for
  27447. * @return the found skeleton or null if not found at all.
  27448. */
  27449. Scene.prototype.getLastSkeletonByID = function (id) {
  27450. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27451. if (this.skeletons[index].id === id) {
  27452. return this.skeletons[index];
  27453. }
  27454. }
  27455. return null;
  27456. };
  27457. /**
  27458. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27459. * @param id defines the id to search for
  27460. * @return the found skeleton or null if not found at all.
  27461. */
  27462. Scene.prototype.getSkeletonById = function (id) {
  27463. for (var index = 0; index < this.skeletons.length; index++) {
  27464. if (this.skeletons[index].id === id) {
  27465. return this.skeletons[index];
  27466. }
  27467. }
  27468. return null;
  27469. };
  27470. /**
  27471. * Gets a skeleton using a given name
  27472. * @param name defines the name to search for
  27473. * @return the found skeleton or null if not found at all.
  27474. */
  27475. Scene.prototype.getSkeletonByName = function (name) {
  27476. for (var index = 0; index < this.skeletons.length; index++) {
  27477. if (this.skeletons[index].name === name) {
  27478. return this.skeletons[index];
  27479. }
  27480. }
  27481. return null;
  27482. };
  27483. /**
  27484. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27485. * @param id defines the id to search for
  27486. * @return the found morph target manager or null if not found at all.
  27487. */
  27488. Scene.prototype.getMorphTargetManagerById = function (id) {
  27489. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27490. if (this.morphTargetManagers[index].uniqueId === id) {
  27491. return this.morphTargetManagers[index];
  27492. }
  27493. }
  27494. return null;
  27495. };
  27496. /**
  27497. * Gets a boolean indicating if the given mesh is active
  27498. * @param mesh defines the mesh to look for
  27499. * @returns true if the mesh is in the active list
  27500. */
  27501. Scene.prototype.isActiveMesh = function (mesh) {
  27502. return (this._activeMeshes.indexOf(mesh) !== -1);
  27503. };
  27504. Object.defineProperty(Scene.prototype, "uid", {
  27505. /**
  27506. * Return a unique id as a string which can serve as an identifier for the scene
  27507. */
  27508. get: function () {
  27509. if (!this._uid) {
  27510. this._uid = BABYLON.Tools.RandomId();
  27511. }
  27512. return this._uid;
  27513. },
  27514. enumerable: true,
  27515. configurable: true
  27516. });
  27517. /**
  27518. * Add an externaly attached data from its key.
  27519. * This method call will fail and return false, if such key already exists.
  27520. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27521. * @param key the unique key that identifies the data
  27522. * @param data the data object to associate to the key for this Engine instance
  27523. * @return true if no such key were already present and the data was added successfully, false otherwise
  27524. */
  27525. Scene.prototype.addExternalData = function (key, data) {
  27526. if (!this._externalData) {
  27527. this._externalData = new BABYLON.StringDictionary();
  27528. }
  27529. return this._externalData.add(key, data);
  27530. };
  27531. /**
  27532. * Get an externaly attached data from its key
  27533. * @param key the unique key that identifies the data
  27534. * @return the associated data, if present (can be null), or undefined if not present
  27535. */
  27536. Scene.prototype.getExternalData = function (key) {
  27537. if (!this._externalData) {
  27538. return null;
  27539. }
  27540. return this._externalData.get(key);
  27541. };
  27542. /**
  27543. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27544. * @param key the unique key that identifies the data
  27545. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27546. * @return the associated data, can be null if the factory returned null.
  27547. */
  27548. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27549. if (!this._externalData) {
  27550. this._externalData = new BABYLON.StringDictionary();
  27551. }
  27552. return this._externalData.getOrAddWithFactory(key, factory);
  27553. };
  27554. /**
  27555. * Remove an externaly attached data from the Engine instance
  27556. * @param key the unique key that identifies the data
  27557. * @return true if the data was successfully removed, false if it doesn't exist
  27558. */
  27559. Scene.prototype.removeExternalData = function (key) {
  27560. return this._externalData.remove(key);
  27561. };
  27562. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27563. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27564. if (mesh.showSubMeshesBoundingBox) {
  27565. var boundingInfo = subMesh.getBoundingInfo();
  27566. if (boundingInfo !== null && boundingInfo !== undefined) {
  27567. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27568. }
  27569. }
  27570. var material = subMesh.getMaterial();
  27571. if (material !== null && material !== undefined) {
  27572. // Render targets
  27573. if (material.getRenderTargetTextures !== undefined) {
  27574. if (this._processedMaterials.indexOf(material) === -1) {
  27575. this._processedMaterials.push(material);
  27576. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27577. }
  27578. }
  27579. // Dispatch
  27580. this._activeIndices.addCount(subMesh.indexCount, false);
  27581. this._renderingManager.dispatch(subMesh, mesh, material);
  27582. }
  27583. }
  27584. };
  27585. /**
  27586. * Clear the processed materials smart array preventing retention point in material dispose.
  27587. */
  27588. Scene.prototype.freeProcessedMaterials = function () {
  27589. this._processedMaterials.dispose();
  27590. };
  27591. /**
  27592. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27593. */
  27594. Scene.prototype.freeActiveMeshes = function () {
  27595. this._activeMeshes.dispose();
  27596. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27597. this.activeCamera._activeMeshes.dispose();
  27598. }
  27599. if (this.activeCameras) {
  27600. for (var i = 0; i < this.activeCameras.length; i++) {
  27601. var activeCamera = this.activeCameras[i];
  27602. if (activeCamera && activeCamera._activeMeshes) {
  27603. activeCamera._activeMeshes.dispose();
  27604. }
  27605. }
  27606. }
  27607. };
  27608. /**
  27609. * Clear the info related to rendering groups preventing retention points during dispose.
  27610. */
  27611. Scene.prototype.freeRenderingGroups = function () {
  27612. if (this._renderingManager) {
  27613. this._renderingManager.freeRenderingGroups();
  27614. }
  27615. if (this.textures) {
  27616. for (var i = 0; i < this.textures.length; i++) {
  27617. var texture = this.textures[i];
  27618. if (texture && texture.renderList) {
  27619. texture.freeRenderingGroups();
  27620. }
  27621. }
  27622. }
  27623. };
  27624. /** @hidden */
  27625. Scene.prototype._isInIntermediateRendering = function () {
  27626. return this._intermediateRendering;
  27627. };
  27628. /**
  27629. * Defines the current active mesh candidate provider
  27630. * @param provider defines the provider to use
  27631. */
  27632. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27633. this._activeMeshCandidateProvider = provider;
  27634. };
  27635. /**
  27636. * Gets the current active mesh candidate provider
  27637. * @returns the current active mesh candidate provider
  27638. */
  27639. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27640. return this._activeMeshCandidateProvider;
  27641. };
  27642. /**
  27643. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27644. * @returns the current scene
  27645. */
  27646. Scene.prototype.freezeActiveMeshes = function () {
  27647. if (!this.activeCamera) {
  27648. return this;
  27649. }
  27650. if (!this._frustumPlanes) {
  27651. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27652. }
  27653. this._evaluateActiveMeshes();
  27654. this._activeMeshesFrozen = true;
  27655. return this;
  27656. };
  27657. /**
  27658. * Use this function to restart evaluating active meshes on every frame
  27659. * @returns the current scene
  27660. */
  27661. Scene.prototype.unfreezeActiveMeshes = function () {
  27662. this._activeMeshesFrozen = false;
  27663. return this;
  27664. };
  27665. Scene.prototype._evaluateActiveMeshes = function () {
  27666. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27667. return;
  27668. }
  27669. if (!this.activeCamera) {
  27670. return;
  27671. }
  27672. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27673. this.activeCamera._activeMeshes.reset();
  27674. this._activeMeshes.reset();
  27675. this._renderingManager.reset();
  27676. this._processedMaterials.reset();
  27677. this._activeParticleSystems.reset();
  27678. this._activeSkeletons.reset();
  27679. this._softwareSkinnedMeshes.reset();
  27680. if (this._boundingBoxRenderer) {
  27681. this._boundingBoxRenderer.reset();
  27682. }
  27683. // Meshes
  27684. var meshes;
  27685. var len;
  27686. var checkIsEnabled = true;
  27687. // Determine mesh candidates
  27688. if (this._activeMeshCandidateProvider !== undefined) {
  27689. // Use _activeMeshCandidateProvider
  27690. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27691. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27692. if (meshes !== undefined) {
  27693. len = meshes.length;
  27694. }
  27695. else {
  27696. len = 0;
  27697. }
  27698. }
  27699. else if (this._selectionOctree !== undefined) {
  27700. // Octree
  27701. var selection = this._selectionOctree.select(this._frustumPlanes);
  27702. meshes = selection.data;
  27703. len = selection.length;
  27704. }
  27705. else {
  27706. // Full scene traversal
  27707. len = this.meshes.length;
  27708. meshes = this.meshes;
  27709. }
  27710. // Check each mesh
  27711. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27712. mesh = meshes[meshIndex];
  27713. if (mesh.isBlocked) {
  27714. continue;
  27715. }
  27716. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27717. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27718. continue;
  27719. }
  27720. mesh.computeWorldMatrix();
  27721. // Intersections
  27722. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27723. this._meshesForIntersections.pushNoDuplicate(mesh);
  27724. }
  27725. // Switch to current LOD
  27726. meshLOD = mesh.getLOD(this.activeCamera);
  27727. if (meshLOD === undefined || meshLOD === null) {
  27728. continue;
  27729. }
  27730. mesh._preActivate();
  27731. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27732. this._activeMeshes.push(mesh);
  27733. this.activeCamera._activeMeshes.push(mesh);
  27734. mesh._activate(this._renderId);
  27735. if (meshLOD !== mesh) {
  27736. meshLOD._activate(this._renderId);
  27737. }
  27738. this._activeMesh(mesh, meshLOD);
  27739. }
  27740. }
  27741. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27742. // Particle systems
  27743. if (this.particlesEnabled) {
  27744. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27745. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27746. var particleSystem = this.particleSystems[particleIndex];
  27747. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27748. continue;
  27749. }
  27750. var emitter = particleSystem.emitter;
  27751. if (!emitter.position || emitter.isEnabled()) {
  27752. this._activeParticleSystems.push(particleSystem);
  27753. particleSystem.animate();
  27754. this._renderingManager.dispatchParticles(particleSystem);
  27755. }
  27756. }
  27757. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27758. }
  27759. };
  27760. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27761. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27762. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27763. mesh.skeleton.prepare();
  27764. }
  27765. if (!mesh.computeBonesUsingShaders) {
  27766. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27767. }
  27768. }
  27769. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27770. var boundingInfo = sourceMesh.getBoundingInfo();
  27771. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27772. }
  27773. if (mesh !== undefined && mesh !== null
  27774. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27775. // Submeshes Octrees
  27776. var len;
  27777. var subMeshes;
  27778. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27779. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27780. len = intersections.length;
  27781. subMeshes = intersections.data;
  27782. }
  27783. else {
  27784. subMeshes = mesh.subMeshes;
  27785. len = subMeshes.length;
  27786. }
  27787. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27788. subMesh = subMeshes[subIndex];
  27789. this._evaluateSubMesh(subMesh, mesh);
  27790. }
  27791. }
  27792. };
  27793. /**
  27794. * Update the transform matrix to update from the current active camera
  27795. * @param force defines a boolean used to force the update even if cache is up to date
  27796. */
  27797. Scene.prototype.updateTransformMatrix = function (force) {
  27798. if (!this.activeCamera) {
  27799. return;
  27800. }
  27801. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27802. };
  27803. /**
  27804. * 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)
  27805. * @param alternateCamera defines the camera to use
  27806. */
  27807. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27808. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27809. };
  27810. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27811. if (camera && camera._skipRendering) {
  27812. return;
  27813. }
  27814. var engine = this._engine;
  27815. this.activeCamera = camera;
  27816. if (!this.activeCamera)
  27817. throw new Error("Active camera not set");
  27818. // Viewport
  27819. engine.setViewport(this.activeCamera.viewport);
  27820. // Camera
  27821. this.resetCachedMaterial();
  27822. this._renderId++;
  27823. this.updateTransformMatrix();
  27824. if (camera._alternateCamera) {
  27825. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27826. this._alternateRendering = true;
  27827. }
  27828. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27829. // Meshes
  27830. this._evaluateActiveMeshes();
  27831. // Software skinning
  27832. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27833. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27834. mesh.applySkeleton(mesh.skeleton);
  27835. }
  27836. // Render targets
  27837. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27838. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27839. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27840. }
  27841. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27842. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27843. }
  27844. if (this.renderTargetsEnabled) {
  27845. this._intermediateRendering = true;
  27846. if (this._renderTargets.length > 0) {
  27847. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27848. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27849. var renderTarget = this._renderTargets.data[renderIndex];
  27850. if (renderTarget._shouldRender()) {
  27851. this._renderId++;
  27852. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27853. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27854. }
  27855. }
  27856. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27857. this._renderId++;
  27858. }
  27859. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27860. var step = _a[_i];
  27861. step.action(this.activeCamera);
  27862. }
  27863. this._intermediateRendering = false;
  27864. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27865. }
  27866. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27867. // Prepare Frame
  27868. if (this.postProcessManager) {
  27869. this.postProcessManager._prepareFrame();
  27870. }
  27871. // Before Camera Draw
  27872. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27873. var step = _c[_b];
  27874. step.action(this.activeCamera);
  27875. }
  27876. // Render
  27877. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27878. this._renderingManager.render(null, null, true, true);
  27879. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27880. // After Camera Draw
  27881. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27882. var step = _e[_d];
  27883. step.action(this.activeCamera);
  27884. }
  27885. // Bounding boxes
  27886. if (this._boundingBoxRenderer) {
  27887. this._boundingBoxRenderer.render();
  27888. }
  27889. // Finalize frame
  27890. if (this.postProcessManager) {
  27891. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27892. }
  27893. // Reset some special arrays
  27894. this._renderTargets.reset();
  27895. this._alternateRendering = false;
  27896. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27897. };
  27898. Scene.prototype._processSubCameras = function (camera) {
  27899. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27900. this._renderForCamera(camera);
  27901. return;
  27902. }
  27903. // rig cameras
  27904. for (var index = 0; index < camera._rigCameras.length; index++) {
  27905. this._renderForCamera(camera._rigCameras[index], camera);
  27906. }
  27907. this.activeCamera = camera;
  27908. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27909. };
  27910. Scene.prototype._checkIntersections = function () {
  27911. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27912. var sourceMesh = this._meshesForIntersections.data[index];
  27913. if (!sourceMesh.actionManager) {
  27914. continue;
  27915. }
  27916. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27917. var action = sourceMesh.actionManager.actions[actionIndex];
  27918. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27919. var parameters = action.getTriggerParameter();
  27920. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27921. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27922. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27923. if (areIntersecting && currentIntersectionInProgress === -1) {
  27924. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27925. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27926. sourceMesh._intersectionsInProgress.push(otherMesh);
  27927. }
  27928. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27929. sourceMesh._intersectionsInProgress.push(otherMesh);
  27930. }
  27931. }
  27932. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27933. //They intersected, and now they don't.
  27934. //is this trigger an exit trigger? execute an event.
  27935. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27936. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27937. }
  27938. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27939. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27940. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27941. return otherMesh === parameterMesh;
  27942. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27943. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27944. }
  27945. }
  27946. }
  27947. }
  27948. }
  27949. };
  27950. /**
  27951. * Render the scene
  27952. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27953. */
  27954. Scene.prototype.render = function (updateCameras) {
  27955. if (updateCameras === void 0) { updateCameras = true; }
  27956. if (this.isDisposed) {
  27957. return;
  27958. }
  27959. // Register components that have been associated lately to the scene.
  27960. this._registerTransientComponents();
  27961. this._activeParticles.fetchNewFrame();
  27962. this._totalVertices.fetchNewFrame();
  27963. this._activeIndices.fetchNewFrame();
  27964. this._activeBones.fetchNewFrame();
  27965. this._meshesForIntersections.reset();
  27966. this.resetCachedMaterial();
  27967. this.onBeforeAnimationsObservable.notifyObservers(this);
  27968. // Actions
  27969. if (this.actionManager) {
  27970. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27971. }
  27972. //Simplification Queue
  27973. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27974. this.simplificationQueue.executeNext();
  27975. }
  27976. if (this._engine.isDeterministicLockStep()) {
  27977. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27978. var defaultFPS = (60.0 / 1000.0);
  27979. var defaultFrameTime = 1000 / 60; // frame time in MS
  27980. if (this._physicsEngine) {
  27981. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27982. }
  27983. var stepsTaken = 0;
  27984. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27985. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27986. internalSteps = Math.min(internalSteps, maxSubSteps);
  27987. do {
  27988. this.onBeforeStepObservable.notifyObservers(this);
  27989. // Animations
  27990. this._animationRatio = defaultFrameTime * defaultFPS;
  27991. this._animate();
  27992. this.onAfterAnimationsObservable.notifyObservers(this);
  27993. // Physics
  27994. if (this._physicsEngine) {
  27995. this.onBeforePhysicsObservable.notifyObservers(this);
  27996. this._physicsEngine._step(defaultFrameTime / 1000);
  27997. this.onAfterPhysicsObservable.notifyObservers(this);
  27998. }
  27999. this.onAfterStepObservable.notifyObservers(this);
  28000. this._currentStepId++;
  28001. stepsTaken++;
  28002. deltaTime -= defaultFrameTime;
  28003. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28004. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28005. }
  28006. else {
  28007. // Animations
  28008. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28009. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28010. this._animate();
  28011. this.onAfterAnimationsObservable.notifyObservers(this);
  28012. // Physics
  28013. if (this._physicsEngine) {
  28014. this.onBeforePhysicsObservable.notifyObservers(this);
  28015. this._physicsEngine._step(deltaTime / 1000.0);
  28016. this.onAfterPhysicsObservable.notifyObservers(this);
  28017. }
  28018. }
  28019. // update gamepad manager
  28020. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  28021. this._gamepadManager._checkGamepadsStatus();
  28022. }
  28023. // Update Cameras
  28024. if (updateCameras) {
  28025. if (this.activeCameras.length > 0) {
  28026. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28027. var camera = this.activeCameras[cameraIndex];
  28028. camera.update();
  28029. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28030. // rig cameras
  28031. for (var index = 0; index < camera._rigCameras.length; index++) {
  28032. camera._rigCameras[index].update();
  28033. }
  28034. }
  28035. }
  28036. }
  28037. else if (this.activeCamera) {
  28038. this.activeCamera.update();
  28039. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28040. // rig cameras
  28041. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28042. this.activeCamera._rigCameras[index].update();
  28043. }
  28044. }
  28045. }
  28046. }
  28047. // Before render
  28048. this.onBeforeRenderObservable.notifyObservers(this);
  28049. // Customs render targets
  28050. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28051. var engine = this.getEngine();
  28052. var currentActiveCamera = this.activeCamera;
  28053. if (this.renderTargetsEnabled) {
  28054. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28055. this._intermediateRendering = true;
  28056. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28057. var renderTarget = this.customRenderTargets[customIndex];
  28058. if (renderTarget._shouldRender()) {
  28059. this._renderId++;
  28060. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28061. if (!this.activeCamera)
  28062. throw new Error("Active camera not set");
  28063. // Viewport
  28064. engine.setViewport(this.activeCamera.viewport);
  28065. // Camera
  28066. this.updateTransformMatrix();
  28067. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28068. }
  28069. }
  28070. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28071. this._intermediateRendering = false;
  28072. this._renderId++;
  28073. }
  28074. // Restore back buffer
  28075. if (this.customRenderTargets.length > 0) {
  28076. engine.restoreDefaultFramebuffer();
  28077. }
  28078. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28079. this.activeCamera = currentActiveCamera;
  28080. // Procedural textures
  28081. if (this.proceduralTexturesEnabled) {
  28082. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28083. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28084. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28085. if (proceduralTexture._shouldRender()) {
  28086. proceduralTexture.render();
  28087. }
  28088. }
  28089. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28090. }
  28091. // Clear
  28092. if (this.autoClearDepthAndStencil || this.autoClear) {
  28093. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28094. }
  28095. // Shadows
  28096. if (this.shadowsEnabled) {
  28097. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28098. var light = this.lights[lightIndex];
  28099. var shadowGenerator = light.getShadowGenerator();
  28100. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28101. var shadowMap = (shadowGenerator.getShadowMap());
  28102. if (this.textures.indexOf(shadowMap) !== -1) {
  28103. this._renderTargets.push(shadowMap);
  28104. }
  28105. }
  28106. }
  28107. }
  28108. // Depth renderer
  28109. for (var key in this._depthRenderer) {
  28110. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28111. }
  28112. // Geometry renderer
  28113. if (this._geometryBufferRenderer) {
  28114. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28115. }
  28116. // RenderPipeline
  28117. if (this._postProcessRenderPipelineManager) {
  28118. this._postProcessRenderPipelineManager.update();
  28119. }
  28120. // Multi-cameras?
  28121. if (this.activeCameras.length > 0) {
  28122. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28123. if (cameraIndex > 0) {
  28124. this._engine.clear(null, false, true, true);
  28125. }
  28126. this._processSubCameras(this.activeCameras[cameraIndex]);
  28127. }
  28128. }
  28129. else {
  28130. if (!this.activeCamera) {
  28131. throw new Error("No camera defined");
  28132. }
  28133. this._processSubCameras(this.activeCamera);
  28134. }
  28135. // Intersection checks
  28136. this._checkIntersections();
  28137. // Update the audio listener attached to the camera
  28138. if (BABYLON.AudioEngine) {
  28139. this._updateAudioParameters();
  28140. }
  28141. // After render
  28142. if (this.afterRender) {
  28143. this.afterRender();
  28144. }
  28145. this.onAfterRenderObservable.notifyObservers(this);
  28146. // Cleaning
  28147. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28148. var data = this._toBeDisposed.data[index];
  28149. if (data) {
  28150. data.dispose();
  28151. }
  28152. this._toBeDisposed[index] = null;
  28153. }
  28154. this._toBeDisposed.reset();
  28155. if (this.dumpNextRenderTargets) {
  28156. this.dumpNextRenderTargets = false;
  28157. }
  28158. this._activeBones.addCount(0, true);
  28159. this._activeIndices.addCount(0, true);
  28160. this._activeParticles.addCount(0, true);
  28161. };
  28162. Scene.prototype._updateAudioParameters = function () {
  28163. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28164. return;
  28165. }
  28166. var listeningCamera;
  28167. var audioEngine = BABYLON.Engine.audioEngine;
  28168. if (this.activeCameras.length > 0) {
  28169. listeningCamera = this.activeCameras[0];
  28170. }
  28171. else {
  28172. listeningCamera = this.activeCamera;
  28173. }
  28174. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28175. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28176. // for VR cameras
  28177. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28178. listeningCamera = listeningCamera.rigCameras[0];
  28179. }
  28180. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28181. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28182. cameraDirection.normalize();
  28183. // To avoid some errors on GearVR
  28184. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28185. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28186. }
  28187. var i;
  28188. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28189. var sound = this.mainSoundTrack.soundCollection[i];
  28190. if (sound.useCustomAttenuation) {
  28191. sound.updateDistanceFromListener();
  28192. }
  28193. }
  28194. for (i = 0; i < this.soundTracks.length; i++) {
  28195. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28196. sound = this.soundTracks[i].soundCollection[j];
  28197. if (sound.useCustomAttenuation) {
  28198. sound.updateDistanceFromListener();
  28199. }
  28200. }
  28201. }
  28202. }
  28203. };
  28204. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28205. // Audio
  28206. /**
  28207. * Gets or sets if audio support is enabled
  28208. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28209. */
  28210. get: function () {
  28211. return this._audioEnabled;
  28212. },
  28213. set: function (value) {
  28214. this._audioEnabled = value;
  28215. if (BABYLON.AudioEngine) {
  28216. if (this._audioEnabled) {
  28217. this._enableAudio();
  28218. }
  28219. else {
  28220. this._disableAudio();
  28221. }
  28222. }
  28223. },
  28224. enumerable: true,
  28225. configurable: true
  28226. });
  28227. Scene.prototype._disableAudio = function () {
  28228. var i;
  28229. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28230. this.mainSoundTrack.soundCollection[i].pause();
  28231. }
  28232. for (i = 0; i < this.soundTracks.length; i++) {
  28233. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28234. this.soundTracks[i].soundCollection[j].pause();
  28235. }
  28236. }
  28237. };
  28238. Scene.prototype._enableAudio = function () {
  28239. var i;
  28240. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28241. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28242. this.mainSoundTrack.soundCollection[i].play();
  28243. }
  28244. }
  28245. for (i = 0; i < this.soundTracks.length; i++) {
  28246. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28247. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28248. this.soundTracks[i].soundCollection[j].play();
  28249. }
  28250. }
  28251. }
  28252. };
  28253. Object.defineProperty(Scene.prototype, "headphone", {
  28254. /**
  28255. * Gets or sets if audio will be output to headphones
  28256. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28257. */
  28258. get: function () {
  28259. return this._headphone;
  28260. },
  28261. set: function (value) {
  28262. this._headphone = value;
  28263. if (BABYLON.AudioEngine) {
  28264. if (this._headphone) {
  28265. this._switchAudioModeForHeadphones();
  28266. }
  28267. else {
  28268. this._switchAudioModeForNormalSpeakers();
  28269. }
  28270. }
  28271. },
  28272. enumerable: true,
  28273. configurable: true
  28274. });
  28275. Scene.prototype._switchAudioModeForHeadphones = function () {
  28276. this.mainSoundTrack.switchPanningModelToHRTF();
  28277. for (var i = 0; i < this.soundTracks.length; i++) {
  28278. this.soundTracks[i].switchPanningModelToHRTF();
  28279. }
  28280. };
  28281. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28282. this.mainSoundTrack.switchPanningModelToEqualPower();
  28283. for (var i = 0; i < this.soundTracks.length; i++) {
  28284. this.soundTracks[i].switchPanningModelToEqualPower();
  28285. }
  28286. };
  28287. /**
  28288. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28289. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28290. * @returns the created depth renderer
  28291. */
  28292. Scene.prototype.enableDepthRenderer = function (camera) {
  28293. camera = camera || this.activeCamera;
  28294. if (!camera) {
  28295. throw "No camera available to enable depth renderer";
  28296. }
  28297. if (!this._depthRenderer[camera.id]) {
  28298. var textureType = 0;
  28299. if (this._engine.getCaps().textureHalfFloatRender) {
  28300. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28301. }
  28302. else if (this._engine.getCaps().textureFloatRender) {
  28303. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28304. }
  28305. else {
  28306. throw "Depth renderer does not support int texture type";
  28307. }
  28308. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28309. }
  28310. return this._depthRenderer[camera.id];
  28311. };
  28312. /**
  28313. * Disables a depth renderer for a given camera
  28314. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28315. */
  28316. Scene.prototype.disableDepthRenderer = function (camera) {
  28317. camera = camera || this.activeCamera;
  28318. if (!camera || !this._depthRenderer[camera.id]) {
  28319. return;
  28320. }
  28321. this._depthRenderer[camera.id].dispose();
  28322. delete this._depthRenderer[camera.id];
  28323. };
  28324. /**
  28325. * Enables a GeometryBufferRender and associates it with the scene
  28326. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28327. * @returns the GeometryBufferRenderer
  28328. */
  28329. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28330. if (ratio === void 0) { ratio = 1; }
  28331. if (this._geometryBufferRenderer) {
  28332. return this._geometryBufferRenderer;
  28333. }
  28334. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28335. if (!this._geometryBufferRenderer.isSupported) {
  28336. this._geometryBufferRenderer = null;
  28337. }
  28338. return this._geometryBufferRenderer;
  28339. };
  28340. /**
  28341. * Disables the GeometryBufferRender associated with the scene
  28342. */
  28343. Scene.prototype.disableGeometryBufferRenderer = function () {
  28344. if (!this._geometryBufferRenderer) {
  28345. return;
  28346. }
  28347. this._geometryBufferRenderer.dispose();
  28348. this._geometryBufferRenderer = null;
  28349. };
  28350. /**
  28351. * Freeze all materials
  28352. * A frozen material will not be updatable but should be faster to render
  28353. */
  28354. Scene.prototype.freezeMaterials = function () {
  28355. for (var i = 0; i < this.materials.length; i++) {
  28356. this.materials[i].freeze();
  28357. }
  28358. };
  28359. /**
  28360. * Unfreeze all materials
  28361. * A frozen material will not be updatable but should be faster to render
  28362. */
  28363. Scene.prototype.unfreezeMaterials = function () {
  28364. for (var i = 0; i < this.materials.length; i++) {
  28365. this.materials[i].unfreeze();
  28366. }
  28367. };
  28368. /**
  28369. * Releases all held ressources
  28370. */
  28371. Scene.prototype.dispose = function () {
  28372. this.beforeRender = null;
  28373. this.afterRender = null;
  28374. this.skeletons = [];
  28375. this.morphTargetManagers = [];
  28376. this._transientComponents = [];
  28377. this._isReadyForMeshStage.clear();
  28378. this._cameraDrawRenderTargetStage.clear();
  28379. this._beforeCameraDrawStage.clear();
  28380. this._beforeRenderingGroupDrawStage.clear();
  28381. this._afterRenderingGroupDrawStage.clear();
  28382. this._afterCameraDrawStage.clear();
  28383. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28384. var component = _a[_i];
  28385. component.dispose();
  28386. }
  28387. this.importedMeshesFiles = new Array();
  28388. this.stopAllAnimations();
  28389. this.resetCachedMaterial();
  28390. for (var key in this._depthRenderer) {
  28391. this._depthRenderer[key].dispose();
  28392. }
  28393. if (this._gamepadManager) {
  28394. this._gamepadManager.dispose();
  28395. this._gamepadManager = null;
  28396. }
  28397. // Smart arrays
  28398. if (this.activeCamera) {
  28399. this.activeCamera._activeMeshes.dispose();
  28400. this.activeCamera = null;
  28401. }
  28402. this._activeMeshes.dispose();
  28403. this._renderingManager.dispose();
  28404. this._processedMaterials.dispose();
  28405. this._activeParticleSystems.dispose();
  28406. this._activeSkeletons.dispose();
  28407. this._softwareSkinnedMeshes.dispose();
  28408. this._renderTargets.dispose();
  28409. this._registeredForLateAnimationBindings.dispose();
  28410. if (this._boundingBoxRenderer) {
  28411. this._boundingBoxRenderer.dispose();
  28412. }
  28413. this._meshesForIntersections.dispose();
  28414. this._toBeDisposed.dispose();
  28415. // Abort active requests
  28416. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28417. var request = _c[_b];
  28418. request.abort();
  28419. }
  28420. // Debug layer
  28421. if (this._debugLayer) {
  28422. this._debugLayer.hide();
  28423. }
  28424. // Events
  28425. this.onDisposeObservable.notifyObservers(this);
  28426. this.onDisposeObservable.clear();
  28427. this.onBeforeRenderObservable.clear();
  28428. this.onAfterRenderObservable.clear();
  28429. this.onBeforeRenderTargetsRenderObservable.clear();
  28430. this.onAfterRenderTargetsRenderObservable.clear();
  28431. this.onAfterStepObservable.clear();
  28432. this.onBeforeStepObservable.clear();
  28433. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28434. this.onAfterActiveMeshesEvaluationObservable.clear();
  28435. this.onBeforeParticlesRenderingObservable.clear();
  28436. this.onAfterParticlesRenderingObservable.clear();
  28437. this.onBeforeSpritesRenderingObservable.clear();
  28438. this.onAfterSpritesRenderingObservable.clear();
  28439. this.onBeforeDrawPhaseObservable.clear();
  28440. this.onAfterDrawPhaseObservable.clear();
  28441. this.onBeforePhysicsObservable.clear();
  28442. this.onAfterPhysicsObservable.clear();
  28443. this.onBeforeAnimationsObservable.clear();
  28444. this.onAfterAnimationsObservable.clear();
  28445. this.onDataLoadedObservable.clear();
  28446. this.detachControl();
  28447. // Release sounds & sounds tracks
  28448. if (BABYLON.AudioEngine) {
  28449. this.disposeSounds();
  28450. }
  28451. // VR Helper
  28452. if (this.VRHelper) {
  28453. this.VRHelper.dispose();
  28454. }
  28455. // Detach cameras
  28456. var canvas = this._engine.getRenderingCanvas();
  28457. if (canvas) {
  28458. var index;
  28459. for (index = 0; index < this.cameras.length; index++) {
  28460. this.cameras[index].detachControl(canvas);
  28461. }
  28462. }
  28463. // Release animation groups
  28464. while (this.animationGroups.length) {
  28465. this.animationGroups[0].dispose();
  28466. }
  28467. // Release lights
  28468. while (this.lights.length) {
  28469. this.lights[0].dispose();
  28470. }
  28471. // Release meshes
  28472. while (this.meshes.length) {
  28473. this.meshes[0].dispose(true);
  28474. }
  28475. while (this.transformNodes.length) {
  28476. this.removeTransformNode(this.transformNodes[0]);
  28477. }
  28478. // Release cameras
  28479. while (this.cameras.length) {
  28480. this.cameras[0].dispose();
  28481. }
  28482. // Release materials
  28483. if (this.defaultMaterial) {
  28484. this.defaultMaterial.dispose();
  28485. }
  28486. while (this.multiMaterials.length) {
  28487. this.multiMaterials[0].dispose();
  28488. }
  28489. while (this.materials.length) {
  28490. this.materials[0].dispose();
  28491. }
  28492. // Release particles
  28493. while (this.particleSystems.length) {
  28494. this.particleSystems[0].dispose();
  28495. }
  28496. // Release sprites
  28497. while (this.spriteManagers.length) {
  28498. this.spriteManagers[0].dispose();
  28499. }
  28500. // Release postProcesses
  28501. while (this.postProcesses.length) {
  28502. this.postProcesses[0].dispose();
  28503. }
  28504. // Release textures
  28505. while (this.textures.length) {
  28506. this.textures[0].dispose();
  28507. }
  28508. // Release UBO
  28509. this._sceneUbo.dispose();
  28510. if (this._alternateSceneUbo) {
  28511. this._alternateSceneUbo.dispose();
  28512. }
  28513. // Post-processes
  28514. this.postProcessManager.dispose();
  28515. if (this._postProcessRenderPipelineManager) {
  28516. this._postProcessRenderPipelineManager.dispose();
  28517. }
  28518. // Physics
  28519. if (this._physicsEngine) {
  28520. this.disablePhysicsEngine();
  28521. }
  28522. // Remove from engine
  28523. index = this._engine.scenes.indexOf(this);
  28524. if (index > -1) {
  28525. this._engine.scenes.splice(index, 1);
  28526. }
  28527. this._engine.wipeCaches(true);
  28528. this._isDisposed = true;
  28529. };
  28530. Object.defineProperty(Scene.prototype, "isDisposed", {
  28531. /**
  28532. * Gets if the scene is already disposed
  28533. */
  28534. get: function () {
  28535. return this._isDisposed;
  28536. },
  28537. enumerable: true,
  28538. configurable: true
  28539. });
  28540. /**
  28541. * Releases sounds & soundtracks
  28542. */
  28543. Scene.prototype.disposeSounds = function () {
  28544. if (!this._mainSoundTrack) {
  28545. return;
  28546. }
  28547. this.mainSoundTrack.dispose();
  28548. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28549. this.soundTracks[scIndex].dispose();
  28550. }
  28551. };
  28552. /**
  28553. * Call this function to reduce memory footprint of the scene.
  28554. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28555. */
  28556. Scene.prototype.clearCachedVertexData = function () {
  28557. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28558. var mesh = this.meshes[meshIndex];
  28559. var geometry = mesh.geometry;
  28560. if (geometry) {
  28561. geometry._indices = [];
  28562. for (var vbName in geometry._vertexBuffers) {
  28563. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28564. continue;
  28565. }
  28566. geometry._vertexBuffers[vbName]._buffer._data = null;
  28567. }
  28568. }
  28569. }
  28570. };
  28571. /**
  28572. * This function will remove the local cached buffer data from texture.
  28573. * It will save memory but will prevent the texture from being rebuilt
  28574. */
  28575. Scene.prototype.cleanCachedTextureBuffer = function () {
  28576. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28577. var baseTexture = _a[_i];
  28578. var buffer = baseTexture._buffer;
  28579. if (buffer) {
  28580. baseTexture._buffer = null;
  28581. }
  28582. }
  28583. };
  28584. // Octrees
  28585. /**
  28586. * Get the world extend vectors with an optional filter
  28587. *
  28588. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28589. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28590. */
  28591. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28592. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28593. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28594. filterPredicate = filterPredicate || (function () { return true; });
  28595. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28596. mesh.computeWorldMatrix(true);
  28597. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28598. return;
  28599. }
  28600. var boundingInfo = mesh.getBoundingInfo();
  28601. var minBox = boundingInfo.boundingBox.minimumWorld;
  28602. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28603. BABYLON.Tools.CheckExtends(minBox, min, max);
  28604. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28605. });
  28606. return {
  28607. min: min,
  28608. max: max
  28609. };
  28610. };
  28611. /**
  28612. * Creates or updates the octree used to boost selection (picking)
  28613. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28614. * @param maxCapacity defines the maximum capacity per leaf
  28615. * @param maxDepth defines the maximum depth of the octree
  28616. * @returns an octree of AbstractMesh
  28617. */
  28618. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28619. if (maxCapacity === void 0) { maxCapacity = 64; }
  28620. if (maxDepth === void 0) { maxDepth = 2; }
  28621. if (!this._selectionOctree) {
  28622. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28623. }
  28624. var worldExtends = this.getWorldExtends();
  28625. // Update octree
  28626. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28627. return this._selectionOctree;
  28628. };
  28629. // Picking
  28630. /**
  28631. * Creates a ray that can be used to pick in the scene
  28632. * @param x defines the x coordinate of the origin (on-screen)
  28633. * @param y defines the y coordinate of the origin (on-screen)
  28634. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28635. * @param camera defines the camera to use for the picking
  28636. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28637. * @returns a Ray
  28638. */
  28639. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28640. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28641. var result = BABYLON.Ray.Zero();
  28642. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28643. return result;
  28644. };
  28645. /**
  28646. * Creates a ray that can be used to pick in the scene
  28647. * @param x defines the x coordinate of the origin (on-screen)
  28648. * @param y defines the y coordinate of the origin (on-screen)
  28649. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28650. * @param result defines the ray where to store the picking ray
  28651. * @param camera defines the camera to use for the picking
  28652. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28653. * @returns the current scene
  28654. */
  28655. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28656. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28657. var engine = this._engine;
  28658. if (!camera) {
  28659. if (!this.activeCamera)
  28660. throw new Error("Active camera not set");
  28661. camera = this.activeCamera;
  28662. }
  28663. var cameraViewport = camera.viewport;
  28664. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28665. // Moving coordinates to local viewport world
  28666. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28667. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28668. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28669. return this;
  28670. };
  28671. /**
  28672. * Creates a ray that can be used to pick in the scene
  28673. * @param x defines the x coordinate of the origin (on-screen)
  28674. * @param y defines the y coordinate of the origin (on-screen)
  28675. * @param camera defines the camera to use for the picking
  28676. * @returns a Ray
  28677. */
  28678. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28679. var result = BABYLON.Ray.Zero();
  28680. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28681. return result;
  28682. };
  28683. /**
  28684. * Creates a ray that can be used to pick in the scene
  28685. * @param x defines the x coordinate of the origin (on-screen)
  28686. * @param y defines the y coordinate of the origin (on-screen)
  28687. * @param result defines the ray where to store the picking ray
  28688. * @param camera defines the camera to use for the picking
  28689. * @returns the current scene
  28690. */
  28691. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28692. if (!BABYLON.PickingInfo) {
  28693. return this;
  28694. }
  28695. var engine = this._engine;
  28696. if (!camera) {
  28697. if (!this.activeCamera)
  28698. throw new Error("Active camera not set");
  28699. camera = this.activeCamera;
  28700. }
  28701. var cameraViewport = camera.viewport;
  28702. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28703. var identity = BABYLON.Matrix.Identity();
  28704. // Moving coordinates to local viewport world
  28705. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28706. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28707. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28708. return this;
  28709. };
  28710. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28711. if (!BABYLON.PickingInfo) {
  28712. return null;
  28713. }
  28714. var pickingInfo = null;
  28715. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28716. var mesh = this.meshes[meshIndex];
  28717. if (predicate) {
  28718. if (!predicate(mesh)) {
  28719. continue;
  28720. }
  28721. }
  28722. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28723. continue;
  28724. }
  28725. var world = mesh.getWorldMatrix();
  28726. var ray = rayFunction(world);
  28727. var result = mesh.intersects(ray, fastCheck);
  28728. if (!result || !result.hit)
  28729. continue;
  28730. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28731. continue;
  28732. pickingInfo = result;
  28733. if (fastCheck) {
  28734. break;
  28735. }
  28736. }
  28737. return pickingInfo || new BABYLON.PickingInfo();
  28738. };
  28739. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28740. if (!BABYLON.PickingInfo) {
  28741. return null;
  28742. }
  28743. var pickingInfos = new Array();
  28744. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28745. var mesh = this.meshes[meshIndex];
  28746. if (predicate) {
  28747. if (!predicate(mesh)) {
  28748. continue;
  28749. }
  28750. }
  28751. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28752. continue;
  28753. }
  28754. var world = mesh.getWorldMatrix();
  28755. var ray = rayFunction(world);
  28756. var result = mesh.intersects(ray, false);
  28757. if (!result || !result.hit)
  28758. continue;
  28759. pickingInfos.push(result);
  28760. }
  28761. return pickingInfos;
  28762. };
  28763. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28764. if (!BABYLON.PickingInfo) {
  28765. return null;
  28766. }
  28767. var pickingInfo = null;
  28768. if (!camera) {
  28769. if (!this.activeCamera) {
  28770. return null;
  28771. }
  28772. camera = this.activeCamera;
  28773. }
  28774. if (this.spriteManagers.length > 0) {
  28775. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28776. var spriteManager = this.spriteManagers[spriteIndex];
  28777. if (!spriteManager.isPickable) {
  28778. continue;
  28779. }
  28780. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28781. if (!result || !result.hit)
  28782. continue;
  28783. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28784. continue;
  28785. pickingInfo = result;
  28786. if (fastCheck) {
  28787. break;
  28788. }
  28789. }
  28790. }
  28791. return pickingInfo || new BABYLON.PickingInfo();
  28792. };
  28793. /** Launch a ray to try to pick a mesh in the scene
  28794. * @param x position on screen
  28795. * @param 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 fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28798. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28799. * @returns a PickingInfo
  28800. */
  28801. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28802. var _this = this;
  28803. if (!BABYLON.PickingInfo) {
  28804. return null;
  28805. }
  28806. var result = this._internalPick(function (world) {
  28807. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28808. return _this._tempPickingRay;
  28809. }, predicate, fastCheck);
  28810. if (result) {
  28811. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28812. }
  28813. return result;
  28814. };
  28815. /** Launch a ray to try to pick a sprite in the scene
  28816. * @param x position on screen
  28817. * @param y position on screen
  28818. * @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
  28819. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28820. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28821. * @returns a PickingInfo
  28822. */
  28823. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28824. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28825. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28826. };
  28827. /** Use the given ray to pick a mesh in the scene
  28828. * @param ray The ray to use to pick meshes
  28829. * @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
  28830. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28831. * @returns a PickingInfo
  28832. */
  28833. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28834. var _this = this;
  28835. var result = this._internalPick(function (world) {
  28836. if (!_this._pickWithRayInverseMatrix) {
  28837. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28838. }
  28839. world.invertToRef(_this._pickWithRayInverseMatrix);
  28840. if (!_this._cachedRayForTransform) {
  28841. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28842. }
  28843. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28844. return _this._cachedRayForTransform;
  28845. }, predicate, fastCheck);
  28846. if (result) {
  28847. result.ray = ray;
  28848. }
  28849. return result;
  28850. };
  28851. /**
  28852. * Launch a ray to try to pick a mesh in the scene
  28853. * @param x X position on screen
  28854. * @param y Y position on screen
  28855. * @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
  28856. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28857. * @returns an array of PickingInfo
  28858. */
  28859. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28860. var _this = this;
  28861. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28862. };
  28863. /**
  28864. * Launch a ray to try to pick a mesh in the scene
  28865. * @param ray Ray to use
  28866. * @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
  28867. * @returns an array of PickingInfo
  28868. */
  28869. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28870. var _this = this;
  28871. return this._internalMultiPick(function (world) {
  28872. if (!_this._pickWithRayInverseMatrix) {
  28873. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28874. }
  28875. world.invertToRef(_this._pickWithRayInverseMatrix);
  28876. if (!_this._cachedRayForTransform) {
  28877. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28878. }
  28879. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28880. return _this._cachedRayForTransform;
  28881. }, predicate);
  28882. };
  28883. /**
  28884. * Force the value of meshUnderPointer
  28885. * @param mesh defines the mesh to use
  28886. */
  28887. Scene.prototype.setPointerOverMesh = function (mesh) {
  28888. if (this._pointerOverMesh === mesh) {
  28889. return;
  28890. }
  28891. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28892. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28893. }
  28894. this._pointerOverMesh = mesh;
  28895. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28896. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28897. }
  28898. };
  28899. /**
  28900. * Gets the mesh under the pointer
  28901. * @returns a Mesh or null if no mesh is under the pointer
  28902. */
  28903. Scene.prototype.getPointerOverMesh = function () {
  28904. return this._pointerOverMesh;
  28905. };
  28906. /**
  28907. * Force the sprite under the pointer
  28908. * @param sprite defines the sprite to use
  28909. */
  28910. Scene.prototype.setPointerOverSprite = function (sprite) {
  28911. if (this._pointerOverSprite === sprite) {
  28912. return;
  28913. }
  28914. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28915. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28916. }
  28917. this._pointerOverSprite = sprite;
  28918. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28919. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28920. }
  28921. };
  28922. /**
  28923. * Gets the sprite under the pointer
  28924. * @returns a Sprite or null if no sprite is under the pointer
  28925. */
  28926. Scene.prototype.getPointerOverSprite = function () {
  28927. return this._pointerOverSprite;
  28928. };
  28929. // Physics
  28930. /**
  28931. * Gets the current physics engine
  28932. * @returns a PhysicsEngine or null if none attached
  28933. */
  28934. Scene.prototype.getPhysicsEngine = function () {
  28935. return this._physicsEngine;
  28936. };
  28937. /**
  28938. * Enables physics to the current scene
  28939. * @param gravity defines the scene's gravity for the physics engine
  28940. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28941. * @return a boolean indicating if the physics engine was initialized
  28942. */
  28943. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28944. if (gravity === void 0) { gravity = null; }
  28945. if (this._physicsEngine) {
  28946. return true;
  28947. }
  28948. try {
  28949. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28950. return true;
  28951. }
  28952. catch (e) {
  28953. BABYLON.Tools.Error(e.message);
  28954. return false;
  28955. }
  28956. };
  28957. /**
  28958. * Disables and disposes the physics engine associated with the scene
  28959. */
  28960. Scene.prototype.disablePhysicsEngine = function () {
  28961. if (!this._physicsEngine) {
  28962. return;
  28963. }
  28964. this._physicsEngine.dispose();
  28965. this._physicsEngine = null;
  28966. };
  28967. /**
  28968. * Gets a boolean indicating if there is an active physics engine
  28969. * @returns a boolean indicating if there is an active physics engine
  28970. */
  28971. Scene.prototype.isPhysicsEnabled = function () {
  28972. return this._physicsEngine !== undefined;
  28973. };
  28974. /**
  28975. * Deletes a physics compound impostor
  28976. * @param compound defines the compound to delete
  28977. */
  28978. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28979. var mesh = compound.parts[0].mesh;
  28980. if (mesh.physicsImpostor) {
  28981. mesh.physicsImpostor.dispose( /*true*/);
  28982. mesh.physicsImpostor = null;
  28983. }
  28984. };
  28985. // Misc.
  28986. /** @hidden */
  28987. Scene.prototype._rebuildGeometries = function () {
  28988. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28989. var geometry = _a[_i];
  28990. geometry._rebuild();
  28991. }
  28992. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28993. var mesh = _c[_b];
  28994. mesh._rebuild();
  28995. }
  28996. if (this.postProcessManager) {
  28997. this.postProcessManager._rebuild();
  28998. }
  28999. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29000. var component = _e[_d];
  29001. component.rebuild();
  29002. }
  29003. if (this._boundingBoxRenderer) {
  29004. this._boundingBoxRenderer._rebuild();
  29005. }
  29006. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29007. var system = _g[_f];
  29008. system.rebuild();
  29009. }
  29010. if (this._postProcessRenderPipelineManager) {
  29011. this._postProcessRenderPipelineManager._rebuild();
  29012. }
  29013. };
  29014. /** @hidden */
  29015. Scene.prototype._rebuildTextures = function () {
  29016. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29017. var texture = _a[_i];
  29018. texture._rebuild();
  29019. }
  29020. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29021. };
  29022. /**
  29023. * Creates a default light for the scene.
  29024. * @param replace Whether to replace the existing lights in the scene.
  29025. */
  29026. Scene.prototype.createDefaultLight = function (replace) {
  29027. if (replace === void 0) { replace = false; }
  29028. // Dispose existing light in replace mode.
  29029. if (replace) {
  29030. if (this.lights) {
  29031. for (var i = 0; i < this.lights.length; i++) {
  29032. this.lights[i].dispose();
  29033. }
  29034. }
  29035. }
  29036. // Light
  29037. if (this.lights.length === 0) {
  29038. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29039. }
  29040. };
  29041. /**
  29042. * Creates a default camera for the scene.
  29043. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29044. * @param replace Whether to replace the existing active camera in the scene.
  29045. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29046. */
  29047. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29048. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29049. if (replace === void 0) { replace = false; }
  29050. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29051. // Dispose existing camera in replace mode.
  29052. if (replace) {
  29053. if (this.activeCamera) {
  29054. this.activeCamera.dispose();
  29055. this.activeCamera = null;
  29056. }
  29057. }
  29058. // Camera
  29059. if (!this.activeCamera) {
  29060. var worldExtends = this.getWorldExtends();
  29061. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29062. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29063. var camera;
  29064. var radius = worldSize.length() * 1.5;
  29065. // empty scene scenario!
  29066. if (!isFinite(radius)) {
  29067. radius = 1;
  29068. worldCenter.copyFromFloats(0, 0, 0);
  29069. }
  29070. if (createArcRotateCamera) {
  29071. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29072. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29073. arcRotateCamera.wheelPrecision = 100 / radius;
  29074. camera = arcRotateCamera;
  29075. }
  29076. else {
  29077. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29078. freeCamera.setTarget(worldCenter);
  29079. camera = freeCamera;
  29080. }
  29081. camera.minZ = radius * 0.01;
  29082. camera.maxZ = radius * 1000;
  29083. camera.speed = radius * 0.2;
  29084. this.activeCamera = camera;
  29085. var canvas = this.getEngine().getRenderingCanvas();
  29086. if (attachCameraControls && canvas) {
  29087. camera.attachControl(canvas);
  29088. }
  29089. }
  29090. };
  29091. /**
  29092. * Creates a default camera and a default light
  29093. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29094. * @param replace defines if the camera and/or light will replace the existing ones
  29095. * @param attachCameraControls defines if attachControl will be called on the new camera
  29096. */
  29097. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29098. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29099. if (replace === void 0) { replace = false; }
  29100. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29101. this.createDefaultLight(replace);
  29102. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29103. };
  29104. /**
  29105. * Creates a new sky box
  29106. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29107. * @param environmentTexture defines the texture to use as environment texture
  29108. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29109. * @param scale defines the overall scale of the skybox
  29110. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29111. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29112. * @returns a new mesh holding the sky box
  29113. */
  29114. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29115. if (pbr === void 0) { pbr = false; }
  29116. if (scale === void 0) { scale = 1000; }
  29117. if (blur === void 0) { blur = 0; }
  29118. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29119. if (!environmentTexture) {
  29120. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29121. return null;
  29122. }
  29123. if (setGlobalEnvTexture) {
  29124. if (environmentTexture) {
  29125. this.environmentTexture = environmentTexture;
  29126. }
  29127. }
  29128. // Skybox
  29129. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29130. if (pbr) {
  29131. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29132. hdrSkyboxMaterial.backFaceCulling = false;
  29133. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29134. if (hdrSkyboxMaterial.reflectionTexture) {
  29135. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29136. }
  29137. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29138. hdrSkyboxMaterial.disableLighting = true;
  29139. hdrSkyboxMaterial.twoSidedLighting = true;
  29140. hdrSkybox.infiniteDistance = true;
  29141. hdrSkybox.material = hdrSkyboxMaterial;
  29142. }
  29143. else {
  29144. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29145. skyboxMaterial.backFaceCulling = false;
  29146. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29147. if (skyboxMaterial.reflectionTexture) {
  29148. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29149. }
  29150. skyboxMaterial.disableLighting = true;
  29151. hdrSkybox.infiniteDistance = true;
  29152. hdrSkybox.material = skyboxMaterial;
  29153. }
  29154. return hdrSkybox;
  29155. };
  29156. /**
  29157. * Creates a new environment
  29158. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29159. * @param options defines the options you can use to configure the environment
  29160. * @returns the new EnvironmentHelper
  29161. */
  29162. Scene.prototype.createDefaultEnvironment = function (options) {
  29163. if (BABYLON.EnvironmentHelper) {
  29164. return new BABYLON.EnvironmentHelper(options, this);
  29165. }
  29166. return null;
  29167. };
  29168. /**
  29169. * Creates a new VREXperienceHelper
  29170. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29171. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29172. * @returns a new VREXperienceHelper
  29173. */
  29174. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29175. if (webVROptions === void 0) { webVROptions = {}; }
  29176. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29177. };
  29178. // Tags
  29179. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29180. if (tagsQuery === undefined) {
  29181. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29182. return list;
  29183. }
  29184. var listByTags = [];
  29185. forEach = forEach || (function (item) { return; });
  29186. for (var i in list) {
  29187. var item = list[i];
  29188. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29189. listByTags.push(item);
  29190. forEach(item);
  29191. }
  29192. }
  29193. return listByTags;
  29194. };
  29195. /**
  29196. * Get a list of meshes by tags
  29197. * @param tagsQuery defines the tags query to use
  29198. * @param forEach defines a predicate used to filter results
  29199. * @returns an array of Mesh
  29200. */
  29201. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29202. return this._getByTags(this.meshes, tagsQuery, forEach);
  29203. };
  29204. /**
  29205. * Get a list of cameras by tags
  29206. * @param tagsQuery defines the tags query to use
  29207. * @param forEach defines a predicate used to filter results
  29208. * @returns an array of Camera
  29209. */
  29210. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29211. return this._getByTags(this.cameras, tagsQuery, forEach);
  29212. };
  29213. /**
  29214. * Get a list of lights by tags
  29215. * @param tagsQuery defines the tags query to use
  29216. * @param forEach defines a predicate used to filter results
  29217. * @returns an array of Light
  29218. */
  29219. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29220. return this._getByTags(this.lights, tagsQuery, forEach);
  29221. };
  29222. /**
  29223. * Get a list of materials by tags
  29224. * @param tagsQuery defines the tags query to use
  29225. * @param forEach defines a predicate used to filter results
  29226. * @returns an array of Material
  29227. */
  29228. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29229. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29230. };
  29231. /**
  29232. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29233. * This allowed control for front to back rendering or reversly depending of the special needs.
  29234. *
  29235. * @param renderingGroupId The rendering group id corresponding to its index
  29236. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29237. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29238. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29239. */
  29240. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29241. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29242. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29243. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29244. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29245. };
  29246. /**
  29247. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29248. *
  29249. * @param renderingGroupId The rendering group id corresponding to its index
  29250. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29251. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29252. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29253. */
  29254. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29255. if (depth === void 0) { depth = true; }
  29256. if (stencil === void 0) { stencil = true; }
  29257. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29258. };
  29259. /**
  29260. * Will flag all materials as dirty to trigger new shader compilation
  29261. * @param flag defines the flag used to specify which material part must be marked as dirty
  29262. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29263. */
  29264. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29265. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29266. var material = _a[_i];
  29267. if (predicate && !predicate(material)) {
  29268. continue;
  29269. }
  29270. material.markAsDirty(flag);
  29271. }
  29272. };
  29273. /** @hidden */
  29274. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29275. var _this = this;
  29276. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29277. this._activeRequests.push(request);
  29278. request.onCompleteObservable.add(function (request) {
  29279. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29280. });
  29281. return request;
  29282. };
  29283. /** @hidden */
  29284. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29285. var _this = this;
  29286. return new Promise(function (resolve, reject) {
  29287. _this._loadFile(url, function (data) {
  29288. resolve(data);
  29289. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29290. reject(exception);
  29291. });
  29292. });
  29293. };
  29294. // Statics
  29295. Scene._FOGMODE_NONE = 0;
  29296. Scene._FOGMODE_EXP = 1;
  29297. Scene._FOGMODE_EXP2 = 2;
  29298. Scene._FOGMODE_LINEAR = 3;
  29299. Scene._uniqueIdCounter = 0;
  29300. /**
  29301. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29302. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29303. */
  29304. Scene.MinDeltaTime = 1.0;
  29305. /**
  29306. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29307. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29308. */
  29309. Scene.MaxDeltaTime = 1000.0;
  29310. /** The distance in pixel that you have to move to prevent some events */
  29311. Scene.DragMovementThreshold = 10; // in pixels
  29312. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29313. Scene.LongPressDelay = 500; // in milliseconds
  29314. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29315. Scene.DoubleClickDelay = 300; // in milliseconds
  29316. /** If you need to check double click without raising a single click at first click, enable this flag */
  29317. Scene.ExclusiveDoubleClickMode = false;
  29318. return Scene;
  29319. }(BABYLON.AbstractScene));
  29320. BABYLON.Scene = Scene;
  29321. })(BABYLON || (BABYLON = {}));
  29322. //# sourceMappingURL=babylon.scene.js.map
  29323. var BABYLON;
  29324. (function (BABYLON) {
  29325. /**
  29326. * Set of assets to keep when moving a scene into an asset container.
  29327. */
  29328. var KeepAssets = /** @class */ (function (_super) {
  29329. __extends(KeepAssets, _super);
  29330. function KeepAssets() {
  29331. return _super !== null && _super.apply(this, arguments) || this;
  29332. }
  29333. return KeepAssets;
  29334. }(BABYLON.AbstractScene));
  29335. BABYLON.KeepAssets = KeepAssets;
  29336. /**
  29337. * Container with a set of assets that can be added or removed from a scene.
  29338. */
  29339. var AssetContainer = /** @class */ (function (_super) {
  29340. __extends(AssetContainer, _super);
  29341. /**
  29342. * Instantiates an AssetContainer.
  29343. * @param scene The scene the AssetContainer belongs to.
  29344. */
  29345. function AssetContainer(scene) {
  29346. var _this = _super.call(this) || this;
  29347. _this.scene = scene;
  29348. return _this;
  29349. }
  29350. /**
  29351. * Adds all the assets from the container to the scene.
  29352. */
  29353. AssetContainer.prototype.addAllToScene = function () {
  29354. var _this = this;
  29355. this.cameras.forEach(function (o) {
  29356. _this.scene.addCamera(o);
  29357. });
  29358. this.lights.forEach(function (o) {
  29359. _this.scene.addLight(o);
  29360. });
  29361. this.meshes.forEach(function (o) {
  29362. _this.scene.addMesh(o);
  29363. });
  29364. this.skeletons.forEach(function (o) {
  29365. _this.scene.addSkeleton(o);
  29366. });
  29367. this.particleSystems.forEach(function (o) {
  29368. _this.scene.addParticleSystem(o);
  29369. });
  29370. this.animations.forEach(function (o) {
  29371. _this.scene.addAnimation(o);
  29372. });
  29373. this.animationGroups.forEach(function (o) {
  29374. _this.scene.addAnimationGroup(o);
  29375. });
  29376. this.multiMaterials.forEach(function (o) {
  29377. _this.scene.addMultiMaterial(o);
  29378. });
  29379. this.materials.forEach(function (o) {
  29380. _this.scene.addMaterial(o);
  29381. });
  29382. this.morphTargetManagers.forEach(function (o) {
  29383. _this.scene.addMorphTargetManager(o);
  29384. });
  29385. this.geometries.forEach(function (o) {
  29386. _this.scene.addGeometry(o);
  29387. });
  29388. this.transformNodes.forEach(function (o) {
  29389. _this.scene.addTransformNode(o);
  29390. });
  29391. this.actionManagers.forEach(function (o) {
  29392. _this.scene.addActionManager(o);
  29393. });
  29394. this.sounds.forEach(function (o) {
  29395. o.play();
  29396. o.autoplay = true;
  29397. _this.scene.mainSoundTrack.AddSound(o);
  29398. });
  29399. this.textures.forEach(function (o) {
  29400. _this.scene.addTexture(o);
  29401. });
  29402. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29403. var component = _a[_i];
  29404. component.addFromContainer(this.scene);
  29405. }
  29406. };
  29407. /**
  29408. * Removes all the assets in the container from the scene
  29409. */
  29410. AssetContainer.prototype.removeAllFromScene = function () {
  29411. var _this = this;
  29412. this.cameras.forEach(function (o) {
  29413. _this.scene.removeCamera(o);
  29414. });
  29415. this.lights.forEach(function (o) {
  29416. _this.scene.removeLight(o);
  29417. });
  29418. this.meshes.forEach(function (o) {
  29419. _this.scene.removeMesh(o);
  29420. });
  29421. this.skeletons.forEach(function (o) {
  29422. _this.scene.removeSkeleton(o);
  29423. });
  29424. this.particleSystems.forEach(function (o) {
  29425. _this.scene.removeParticleSystem(o);
  29426. });
  29427. this.animations.forEach(function (o) {
  29428. _this.scene.removeAnimation(o);
  29429. });
  29430. this.animationGroups.forEach(function (o) {
  29431. _this.scene.removeAnimationGroup(o);
  29432. });
  29433. this.multiMaterials.forEach(function (o) {
  29434. _this.scene.removeMultiMaterial(o);
  29435. });
  29436. this.materials.forEach(function (o) {
  29437. _this.scene.removeMaterial(o);
  29438. });
  29439. this.morphTargetManagers.forEach(function (o) {
  29440. _this.scene.removeMorphTargetManager(o);
  29441. });
  29442. this.geometries.forEach(function (o) {
  29443. _this.scene.removeGeometry(o);
  29444. });
  29445. this.transformNodes.forEach(function (o) {
  29446. _this.scene.removeTransformNode(o);
  29447. });
  29448. this.actionManagers.forEach(function (o) {
  29449. _this.scene.removeActionManager(o);
  29450. });
  29451. this.sounds.forEach(function (o) {
  29452. o.stop();
  29453. o.autoplay = false;
  29454. _this.scene.mainSoundTrack.RemoveSound(o);
  29455. });
  29456. this.textures.forEach(function (o) {
  29457. _this.scene.removeTexture(o);
  29458. });
  29459. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29460. var component = _a[_i];
  29461. component.removeFromContainer(this.scene);
  29462. }
  29463. };
  29464. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29465. if (!sourceAssets) {
  29466. return;
  29467. }
  29468. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29469. var asset = sourceAssets_1[_i];
  29470. var move = true;
  29471. if (keepAssets) {
  29472. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29473. var keepAsset = keepAssets_1[_a];
  29474. if (asset === keepAsset) {
  29475. move = false;
  29476. break;
  29477. }
  29478. }
  29479. }
  29480. if (move) {
  29481. targetAssets.push(asset);
  29482. }
  29483. }
  29484. };
  29485. /**
  29486. * Removes all the assets contained in the scene and adds them to the container.
  29487. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29488. */
  29489. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29490. if (keepAssets === undefined) {
  29491. keepAssets = new KeepAssets();
  29492. }
  29493. for (var key in this) {
  29494. if (this.hasOwnProperty(key)) {
  29495. this[key] = this[key] || [];
  29496. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29497. }
  29498. }
  29499. this.removeAllFromScene();
  29500. };
  29501. /**
  29502. * 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.
  29503. * @returns the root mesh
  29504. */
  29505. AssetContainer.prototype.createRootMesh = function () {
  29506. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29507. this.meshes.forEach(function (m) {
  29508. if (!m.parent) {
  29509. rootMesh.addChild(m);
  29510. }
  29511. });
  29512. this.meshes.unshift(rootMesh);
  29513. return rootMesh;
  29514. };
  29515. return AssetContainer;
  29516. }(BABYLON.AbstractScene));
  29517. BABYLON.AssetContainer = AssetContainer;
  29518. })(BABYLON || (BABYLON = {}));
  29519. //# sourceMappingURL=babylon.assetContainer.js.map
  29520. var BABYLON;
  29521. (function (BABYLON) {
  29522. var Buffer = /** @class */ (function () {
  29523. /**
  29524. * Constructor
  29525. * @param engine the engine
  29526. * @param data the data to use for this buffer
  29527. * @param updatable whether the data is updatable
  29528. * @param stride the stride (optional)
  29529. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29530. * @param instanced whether the buffer is instanced (optional)
  29531. * @param useBytes set to true if the stride in in bytes (optional)
  29532. */
  29533. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29534. if (stride === void 0) { stride = 0; }
  29535. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29536. if (instanced === void 0) { instanced = false; }
  29537. if (useBytes === void 0) { useBytes = false; }
  29538. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29539. this._engine = engine.getScene().getEngine();
  29540. }
  29541. else {
  29542. this._engine = engine;
  29543. }
  29544. this._updatable = updatable;
  29545. this._instanced = instanced;
  29546. this._data = data;
  29547. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29548. if (!postponeInternalCreation) { // by default
  29549. this.create();
  29550. }
  29551. }
  29552. /**
  29553. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29554. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29555. * @param offset defines offset in the buffer (0 by default)
  29556. * @param size defines the size in floats of attributes (position is 3 for instance)
  29557. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29558. * @param instanced defines if the vertex buffer contains indexed data
  29559. * @param useBytes defines if the offset and stride are in bytes
  29560. * @returns the new vertex buffer
  29561. */
  29562. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29563. if (useBytes === void 0) { useBytes = false; }
  29564. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29565. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29566. // a lot of these parameters are ignored as they are overriden by the buffer
  29567. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29568. };
  29569. // Properties
  29570. Buffer.prototype.isUpdatable = function () {
  29571. return this._updatable;
  29572. };
  29573. Buffer.prototype.getData = function () {
  29574. return this._data;
  29575. };
  29576. Buffer.prototype.getBuffer = function () {
  29577. return this._buffer;
  29578. };
  29579. /**
  29580. * Gets the stride in float32 units (i.e. byte stride / 4).
  29581. * May not be an integer if the byte stride is not divisible by 4.
  29582. * DEPRECATED. Use byteStride instead.
  29583. * @returns the stride in float32 units
  29584. */
  29585. Buffer.prototype.getStrideSize = function () {
  29586. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29587. };
  29588. // Methods
  29589. Buffer.prototype.create = function (data) {
  29590. if (data === void 0) { data = null; }
  29591. if (!data && this._buffer) {
  29592. return; // nothing to do
  29593. }
  29594. data = data || this._data;
  29595. if (!data) {
  29596. return;
  29597. }
  29598. if (!this._buffer) { // create buffer
  29599. if (this._updatable) {
  29600. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29601. this._data = data;
  29602. }
  29603. else {
  29604. this._buffer = this._engine.createVertexBuffer(data);
  29605. }
  29606. }
  29607. else if (this._updatable) { // update buffer
  29608. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29609. this._data = data;
  29610. }
  29611. };
  29612. Buffer.prototype._rebuild = function () {
  29613. this._buffer = null;
  29614. this.create(this._data);
  29615. };
  29616. Buffer.prototype.update = function (data) {
  29617. this.create(data);
  29618. };
  29619. /**
  29620. * Updates the data directly.
  29621. * @param data the new data
  29622. * @param offset the new offset
  29623. * @param vertexCount the vertex count (optional)
  29624. * @param useBytes set to true if the offset is in bytes
  29625. */
  29626. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29627. if (useBytes === void 0) { useBytes = false; }
  29628. if (!this._buffer) {
  29629. return;
  29630. }
  29631. if (this._updatable) { // update buffer
  29632. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29633. this._data = null;
  29634. }
  29635. };
  29636. Buffer.prototype.dispose = function () {
  29637. if (!this._buffer) {
  29638. return;
  29639. }
  29640. if (this._engine._releaseBuffer(this._buffer)) {
  29641. this._buffer = null;
  29642. }
  29643. };
  29644. return Buffer;
  29645. }());
  29646. BABYLON.Buffer = Buffer;
  29647. })(BABYLON || (BABYLON = {}));
  29648. //# sourceMappingURL=babylon.buffer.js.map
  29649. var BABYLON;
  29650. (function (BABYLON) {
  29651. var VertexBuffer = /** @class */ (function () {
  29652. /**
  29653. * Constructor
  29654. * @param engine the engine
  29655. * @param data the data to use for this vertex buffer
  29656. * @param kind the vertex buffer kind
  29657. * @param updatable whether the data is updatable
  29658. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29659. * @param stride the stride (optional)
  29660. * @param instanced whether the buffer is instanced (optional)
  29661. * @param offset the offset of the data (optional)
  29662. * @param size the number of components (optional)
  29663. * @param type the type of the component (optional)
  29664. * @param normalized whether the data contains normalized data (optional)
  29665. * @param useBytes set to true if stride and offset are in bytes (optional)
  29666. */
  29667. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29668. if (normalized === void 0) { normalized = false; }
  29669. if (useBytes === void 0) { useBytes = false; }
  29670. if (data instanceof BABYLON.Buffer) {
  29671. this._buffer = data;
  29672. this._ownsBuffer = false;
  29673. }
  29674. else {
  29675. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29676. this._ownsBuffer = true;
  29677. }
  29678. this._kind = kind;
  29679. if (type == undefined) {
  29680. var data_1 = this.getData();
  29681. this.type = VertexBuffer.FLOAT;
  29682. if (data_1 instanceof Int8Array)
  29683. this.type = VertexBuffer.BYTE;
  29684. else if (data_1 instanceof Uint8Array)
  29685. this.type = VertexBuffer.UNSIGNED_BYTE;
  29686. else if (data_1 instanceof Int16Array)
  29687. this.type = VertexBuffer.SHORT;
  29688. else if (data_1 instanceof Uint16Array)
  29689. this.type = VertexBuffer.UNSIGNED_SHORT;
  29690. else if (data_1 instanceof Int32Array)
  29691. this.type = VertexBuffer.INT;
  29692. else if (data_1 instanceof Uint32Array)
  29693. this.type = VertexBuffer.UNSIGNED_INT;
  29694. }
  29695. else {
  29696. this.type = type;
  29697. }
  29698. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29699. if (useBytes) {
  29700. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29701. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29702. this.byteOffset = offset || 0;
  29703. }
  29704. else {
  29705. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29706. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29707. this.byteOffset = (offset || 0) * typeByteLength;
  29708. }
  29709. this.normalized = normalized;
  29710. this._instanced = instanced !== undefined ? instanced : false;
  29711. this._instanceDivisor = instanced ? 1 : 0;
  29712. }
  29713. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29714. /**
  29715. * Gets or sets the instance divisor when in instanced mode
  29716. */
  29717. get: function () {
  29718. return this._instanceDivisor;
  29719. },
  29720. set: function (value) {
  29721. this._instanceDivisor = value;
  29722. if (value == 0) {
  29723. this._instanced = false;
  29724. }
  29725. else {
  29726. this._instanced = true;
  29727. }
  29728. },
  29729. enumerable: true,
  29730. configurable: true
  29731. });
  29732. VertexBuffer.prototype._rebuild = function () {
  29733. if (!this._buffer) {
  29734. return;
  29735. }
  29736. this._buffer._rebuild();
  29737. };
  29738. /**
  29739. * Returns the kind of the VertexBuffer (string).
  29740. */
  29741. VertexBuffer.prototype.getKind = function () {
  29742. return this._kind;
  29743. };
  29744. // Properties
  29745. /**
  29746. * Boolean : is the VertexBuffer updatable ?
  29747. */
  29748. VertexBuffer.prototype.isUpdatable = function () {
  29749. return this._buffer.isUpdatable();
  29750. };
  29751. /**
  29752. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29753. */
  29754. VertexBuffer.prototype.getData = function () {
  29755. return this._buffer.getData();
  29756. };
  29757. /**
  29758. * Returns the WebGLBuffer associated to the VertexBuffer.
  29759. */
  29760. VertexBuffer.prototype.getBuffer = function () {
  29761. return this._buffer.getBuffer();
  29762. };
  29763. /**
  29764. * Returns the stride as a multiple of the type byte length.
  29765. * DEPRECATED. Use byteStride instead.
  29766. */
  29767. VertexBuffer.prototype.getStrideSize = function () {
  29768. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29769. };
  29770. /**
  29771. * Returns the offset as a multiple of the type byte length.
  29772. * DEPRECATED. Use byteOffset instead.
  29773. */
  29774. VertexBuffer.prototype.getOffset = function () {
  29775. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29776. };
  29777. /**
  29778. * Returns the number of components per vertex attribute (integer).
  29779. */
  29780. VertexBuffer.prototype.getSize = function () {
  29781. return this._size;
  29782. };
  29783. /**
  29784. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29785. */
  29786. VertexBuffer.prototype.getIsInstanced = function () {
  29787. return this._instanced;
  29788. };
  29789. /**
  29790. * Returns the instancing divisor, zero for non-instanced (integer).
  29791. */
  29792. VertexBuffer.prototype.getInstanceDivisor = function () {
  29793. return this._instanceDivisor;
  29794. };
  29795. // Methods
  29796. /**
  29797. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29798. * Returns the created WebGLBuffer.
  29799. */
  29800. VertexBuffer.prototype.create = function (data) {
  29801. return this._buffer.create(data);
  29802. };
  29803. /**
  29804. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29805. * This function will create a new buffer if the current one is not updatable
  29806. * Returns the updated WebGLBuffer.
  29807. */
  29808. VertexBuffer.prototype.update = function (data) {
  29809. return this._buffer.update(data);
  29810. };
  29811. /**
  29812. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29813. * Returns the directly updated WebGLBuffer.
  29814. * @param data the new data
  29815. * @param offset the new offset
  29816. * @param useBytes set to true if the offset is in bytes
  29817. */
  29818. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29819. if (useBytes === void 0) { useBytes = false; }
  29820. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29821. };
  29822. /**
  29823. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29824. */
  29825. VertexBuffer.prototype.dispose = function () {
  29826. if (this._ownsBuffer) {
  29827. this._buffer.dispose();
  29828. }
  29829. };
  29830. /**
  29831. * Enumerates each value of this vertex buffer as numbers.
  29832. * @param count the number of values to enumerate
  29833. * @param callback the callback function called for each value
  29834. */
  29835. VertexBuffer.prototype.forEach = function (count, callback) {
  29836. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29837. };
  29838. Object.defineProperty(VertexBuffer, "PositionKind", {
  29839. get: function () {
  29840. return VertexBuffer._PositionKind;
  29841. },
  29842. enumerable: true,
  29843. configurable: true
  29844. });
  29845. Object.defineProperty(VertexBuffer, "NormalKind", {
  29846. get: function () {
  29847. return VertexBuffer._NormalKind;
  29848. },
  29849. enumerable: true,
  29850. configurable: true
  29851. });
  29852. Object.defineProperty(VertexBuffer, "TangentKind", {
  29853. get: function () {
  29854. return VertexBuffer._TangentKind;
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. Object.defineProperty(VertexBuffer, "UVKind", {
  29860. get: function () {
  29861. return VertexBuffer._UVKind;
  29862. },
  29863. enumerable: true,
  29864. configurable: true
  29865. });
  29866. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29867. get: function () {
  29868. return VertexBuffer._UV2Kind;
  29869. },
  29870. enumerable: true,
  29871. configurable: true
  29872. });
  29873. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29874. get: function () {
  29875. return VertexBuffer._UV3Kind;
  29876. },
  29877. enumerable: true,
  29878. configurable: true
  29879. });
  29880. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29881. get: function () {
  29882. return VertexBuffer._UV4Kind;
  29883. },
  29884. enumerable: true,
  29885. configurable: true
  29886. });
  29887. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29888. get: function () {
  29889. return VertexBuffer._UV5Kind;
  29890. },
  29891. enumerable: true,
  29892. configurable: true
  29893. });
  29894. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29895. get: function () {
  29896. return VertexBuffer._UV6Kind;
  29897. },
  29898. enumerable: true,
  29899. configurable: true
  29900. });
  29901. Object.defineProperty(VertexBuffer, "ColorKind", {
  29902. get: function () {
  29903. return VertexBuffer._ColorKind;
  29904. },
  29905. enumerable: true,
  29906. configurable: true
  29907. });
  29908. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29909. get: function () {
  29910. return VertexBuffer._MatricesIndicesKind;
  29911. },
  29912. enumerable: true,
  29913. configurable: true
  29914. });
  29915. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29916. get: function () {
  29917. return VertexBuffer._MatricesWeightsKind;
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29923. get: function () {
  29924. return VertexBuffer._MatricesIndicesExtraKind;
  29925. },
  29926. enumerable: true,
  29927. configurable: true
  29928. });
  29929. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29930. get: function () {
  29931. return VertexBuffer._MatricesWeightsExtraKind;
  29932. },
  29933. enumerable: true,
  29934. configurable: true
  29935. });
  29936. /**
  29937. * Deduces the stride given a kind.
  29938. * @param kind The kind string to deduce
  29939. * @returns The deduced stride
  29940. */
  29941. VertexBuffer.DeduceStride = function (kind) {
  29942. switch (kind) {
  29943. case VertexBuffer.UVKind:
  29944. case VertexBuffer.UV2Kind:
  29945. case VertexBuffer.UV3Kind:
  29946. case VertexBuffer.UV4Kind:
  29947. case VertexBuffer.UV5Kind:
  29948. case VertexBuffer.UV6Kind:
  29949. return 2;
  29950. case VertexBuffer.NormalKind:
  29951. case VertexBuffer.PositionKind:
  29952. return 3;
  29953. case VertexBuffer.ColorKind:
  29954. case VertexBuffer.MatricesIndicesKind:
  29955. case VertexBuffer.MatricesIndicesExtraKind:
  29956. case VertexBuffer.MatricesWeightsKind:
  29957. case VertexBuffer.MatricesWeightsExtraKind:
  29958. case VertexBuffer.TangentKind:
  29959. return 4;
  29960. default:
  29961. throw new Error("Invalid kind '" + kind + "'");
  29962. }
  29963. };
  29964. /**
  29965. * Gets the byte length of the given type.
  29966. * @param type the type
  29967. * @returns the number of bytes
  29968. */
  29969. VertexBuffer.GetTypeByteLength = function (type) {
  29970. switch (type) {
  29971. case VertexBuffer.BYTE:
  29972. case VertexBuffer.UNSIGNED_BYTE:
  29973. return 1;
  29974. case VertexBuffer.SHORT:
  29975. case VertexBuffer.UNSIGNED_SHORT:
  29976. return 2;
  29977. case VertexBuffer.INT:
  29978. case VertexBuffer.FLOAT:
  29979. return 4;
  29980. default:
  29981. throw new Error("Invalid type '" + type + "'");
  29982. }
  29983. };
  29984. /**
  29985. * Enumerates each value of the given parameters as numbers.
  29986. * @param data the data to enumerate
  29987. * @param byteOffset the byte offset of the data
  29988. * @param byteStride the byte stride of the data
  29989. * @param componentCount the number of components per element
  29990. * @param componentType the type of the component
  29991. * @param count the total number of components
  29992. * @param normalized whether the data is normalized
  29993. * @param callback the callback function called for each value
  29994. */
  29995. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29996. if (data instanceof Array) {
  29997. var offset = byteOffset / 4;
  29998. var stride = byteStride / 4;
  29999. for (var index = 0; index < count; index += componentCount) {
  30000. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30001. callback(data[offset + componentIndex], index + componentIndex);
  30002. }
  30003. offset += stride;
  30004. }
  30005. }
  30006. else {
  30007. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30008. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30009. for (var index = 0; index < count; index += componentCount) {
  30010. var componentByteOffset = byteOffset;
  30011. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30012. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30013. callback(value, index + componentIndex);
  30014. componentByteOffset += componentByteLength;
  30015. }
  30016. byteOffset += byteStride;
  30017. }
  30018. }
  30019. };
  30020. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30021. switch (type) {
  30022. case VertexBuffer.BYTE: {
  30023. var value = dataView.getInt8(byteOffset);
  30024. if (normalized) {
  30025. value = Math.max(value / 127, -1);
  30026. }
  30027. return value;
  30028. }
  30029. case VertexBuffer.UNSIGNED_BYTE: {
  30030. var value = dataView.getUint8(byteOffset);
  30031. if (normalized) {
  30032. value = value / 255;
  30033. }
  30034. return value;
  30035. }
  30036. case VertexBuffer.SHORT: {
  30037. var value = dataView.getInt16(byteOffset, true);
  30038. if (normalized) {
  30039. value = Math.max(value / 16383, -1);
  30040. }
  30041. return value;
  30042. }
  30043. case VertexBuffer.UNSIGNED_SHORT: {
  30044. var value = dataView.getUint16(byteOffset, true);
  30045. if (normalized) {
  30046. value = value / 65535;
  30047. }
  30048. return value;
  30049. }
  30050. case VertexBuffer.FLOAT: {
  30051. return dataView.getFloat32(byteOffset, true);
  30052. }
  30053. default: {
  30054. throw new Error("Invalid component type " + type);
  30055. }
  30056. }
  30057. };
  30058. /**
  30059. * The byte type.
  30060. */
  30061. VertexBuffer.BYTE = 5120;
  30062. /**
  30063. * The unsigned byte type.
  30064. */
  30065. VertexBuffer.UNSIGNED_BYTE = 5121;
  30066. /**
  30067. * The short type.
  30068. */
  30069. VertexBuffer.SHORT = 5122;
  30070. /**
  30071. * The unsigned short type.
  30072. */
  30073. VertexBuffer.UNSIGNED_SHORT = 5123;
  30074. /**
  30075. * The integer type.
  30076. */
  30077. VertexBuffer.INT = 5124;
  30078. /**
  30079. * The unsigned integer type.
  30080. */
  30081. VertexBuffer.UNSIGNED_INT = 5125;
  30082. /**
  30083. * The float type.
  30084. */
  30085. VertexBuffer.FLOAT = 5126;
  30086. // Enums
  30087. VertexBuffer._PositionKind = "position";
  30088. VertexBuffer._NormalKind = "normal";
  30089. VertexBuffer._TangentKind = "tangent";
  30090. VertexBuffer._UVKind = "uv";
  30091. VertexBuffer._UV2Kind = "uv2";
  30092. VertexBuffer._UV3Kind = "uv3";
  30093. VertexBuffer._UV4Kind = "uv4";
  30094. VertexBuffer._UV5Kind = "uv5";
  30095. VertexBuffer._UV6Kind = "uv6";
  30096. VertexBuffer._ColorKind = "color";
  30097. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30098. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30099. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30100. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30101. return VertexBuffer;
  30102. }());
  30103. BABYLON.VertexBuffer = VertexBuffer;
  30104. })(BABYLON || (BABYLON = {}));
  30105. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30106. var BABYLON;
  30107. (function (BABYLON) {
  30108. /**
  30109. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30110. */
  30111. var DummyInternalTextureTracker = /** @class */ (function () {
  30112. function DummyInternalTextureTracker() {
  30113. /**
  30114. * Gets or set the previous tracker in the list
  30115. */
  30116. this.previous = null;
  30117. /**
  30118. * Gets or set the next tracker in the list
  30119. */
  30120. this.next = null;
  30121. }
  30122. return DummyInternalTextureTracker;
  30123. }());
  30124. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30125. })(BABYLON || (BABYLON = {}));
  30126. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30127. var BABYLON;
  30128. (function (BABYLON) {
  30129. /**
  30130. * Class used to store data associated with WebGL texture data for the engine
  30131. * This class should not be used directly
  30132. */
  30133. var InternalTexture = /** @class */ (function () {
  30134. /**
  30135. * Creates a new InternalTexture
  30136. * @param engine defines the engine to use
  30137. * @param dataSource defines the type of data that will be used
  30138. */
  30139. function InternalTexture(engine, dataSource) {
  30140. /**
  30141. * Observable called when the texture is loaded
  30142. */
  30143. this.onLoadedObservable = new BABYLON.Observable();
  30144. /**
  30145. * Gets or set the previous tracker in the list
  30146. */
  30147. this.previous = null;
  30148. /**
  30149. * Gets or set the next tracker in the list
  30150. */
  30151. this.next = null;
  30152. // Private
  30153. /** @hidden */
  30154. this._initialSlot = -1;
  30155. /** @hidden */
  30156. this._designatedSlot = -1;
  30157. /** @hidden */
  30158. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30159. /** @hidden */
  30160. this._comparisonFunction = 0;
  30161. /** @hidden */
  30162. this._sphericalPolynomial = null;
  30163. /** @hidden */
  30164. this._lodGenerationScale = 0;
  30165. /** @hidden */
  30166. this._lodGenerationOffset = 0;
  30167. /** @hidden */
  30168. this._isRGBD = false;
  30169. /** @hidden */
  30170. this._references = 1;
  30171. this._engine = engine;
  30172. this._dataSource = dataSource;
  30173. this._webGLTexture = engine._createTexture();
  30174. }
  30175. /**
  30176. * Gets the Engine the texture belongs to.
  30177. * @returns The babylon engine
  30178. */
  30179. InternalTexture.prototype.getEngine = function () {
  30180. return this._engine;
  30181. };
  30182. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30183. /**
  30184. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30185. */
  30186. get: function () {
  30187. return this._dataSource;
  30188. },
  30189. enumerable: true,
  30190. configurable: true
  30191. });
  30192. /**
  30193. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30194. */
  30195. InternalTexture.prototype.incrementReferences = function () {
  30196. this._references++;
  30197. };
  30198. /**
  30199. * Change the size of the texture (not the size of the content)
  30200. * @param width defines the new width
  30201. * @param height defines the new height
  30202. * @param depth defines the new depth (1 by default)
  30203. */
  30204. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30205. if (depth === void 0) { depth = 1; }
  30206. this.width = width;
  30207. this.height = height;
  30208. this.depth = depth;
  30209. this.baseWidth = width;
  30210. this.baseHeight = height;
  30211. this.baseDepth = depth;
  30212. this._size = width * height * depth;
  30213. };
  30214. /** @hidden */
  30215. InternalTexture.prototype._rebuild = function () {
  30216. var _this = this;
  30217. var proxy;
  30218. this.isReady = false;
  30219. this._cachedCoordinatesMode = null;
  30220. this._cachedWrapU = null;
  30221. this._cachedWrapV = null;
  30222. this._cachedAnisotropicFilteringLevel = null;
  30223. switch (this._dataSource) {
  30224. case InternalTexture.DATASOURCE_TEMP:
  30225. return;
  30226. case InternalTexture.DATASOURCE_URL:
  30227. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30228. _this.isReady = true;
  30229. }, null, this._buffer, undefined, this.format);
  30230. proxy._swapAndDie(this);
  30231. return;
  30232. case InternalTexture.DATASOURCE_RAW:
  30233. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30234. proxy._swapAndDie(this);
  30235. this.isReady = true;
  30236. return;
  30237. case InternalTexture.DATASOURCE_RAW3D:
  30238. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30239. proxy._swapAndDie(this);
  30240. this.isReady = true;
  30241. return;
  30242. case InternalTexture.DATASOURCE_DYNAMIC:
  30243. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30244. proxy._swapAndDie(this);
  30245. // The engine will make sure to update content so no need to flag it as isReady = true
  30246. return;
  30247. case InternalTexture.DATASOURCE_RENDERTARGET:
  30248. var options = new BABYLON.RenderTargetCreationOptions();
  30249. options.generateDepthBuffer = this._generateDepthBuffer;
  30250. options.generateMipMaps = this.generateMipMaps;
  30251. options.generateStencilBuffer = this._generateStencilBuffer;
  30252. options.samplingMode = this.samplingMode;
  30253. options.type = this.type;
  30254. if (this.isCube) {
  30255. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30256. }
  30257. else {
  30258. var size = {
  30259. width: this.width,
  30260. height: this.height
  30261. };
  30262. proxy = this._engine.createRenderTargetTexture(size, options);
  30263. }
  30264. proxy._swapAndDie(this);
  30265. this.isReady = true;
  30266. return;
  30267. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30268. var depthTextureOptions = {
  30269. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30270. comparisonFunction: this._comparisonFunction,
  30271. generateStencil: this._generateStencilBuffer,
  30272. isCube: this.isCube
  30273. };
  30274. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30275. proxy._swapAndDie(this);
  30276. this.isReady = true;
  30277. return;
  30278. case InternalTexture.DATASOURCE_CUBE:
  30279. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30280. _this.isReady = true;
  30281. }, null, this.format, this._extension);
  30282. proxy._swapAndDie(this);
  30283. return;
  30284. case InternalTexture.DATASOURCE_CUBERAW:
  30285. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30286. proxy._swapAndDie(this);
  30287. this.isReady = true;
  30288. return;
  30289. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30290. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30291. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30292. _this.isReady = true;
  30293. });
  30294. proxy._swapAndDie(this);
  30295. return;
  30296. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30297. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30298. if (proxy) {
  30299. proxy._swapAndDie(_this);
  30300. }
  30301. _this.isReady = true;
  30302. }, null, this.format, this._extension);
  30303. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30304. return;
  30305. }
  30306. };
  30307. InternalTexture.prototype._swapAndDie = function (target) {
  30308. target._webGLTexture = this._webGLTexture;
  30309. if (this._framebuffer) {
  30310. target._framebuffer = this._framebuffer;
  30311. }
  30312. if (this._depthStencilBuffer) {
  30313. target._depthStencilBuffer = this._depthStencilBuffer;
  30314. }
  30315. if (this._lodTextureHigh) {
  30316. if (target._lodTextureHigh) {
  30317. target._lodTextureHigh.dispose();
  30318. }
  30319. target._lodTextureHigh = this._lodTextureHigh;
  30320. }
  30321. if (this._lodTextureMid) {
  30322. if (target._lodTextureMid) {
  30323. target._lodTextureMid.dispose();
  30324. }
  30325. target._lodTextureMid = this._lodTextureMid;
  30326. }
  30327. if (this._lodTextureLow) {
  30328. if (target._lodTextureLow) {
  30329. target._lodTextureLow.dispose();
  30330. }
  30331. target._lodTextureLow = this._lodTextureLow;
  30332. }
  30333. var cache = this._engine.getLoadedTexturesCache();
  30334. var index = cache.indexOf(this);
  30335. if (index !== -1) {
  30336. cache.splice(index, 1);
  30337. }
  30338. };
  30339. /**
  30340. * Dispose the current allocated resources
  30341. */
  30342. InternalTexture.prototype.dispose = function () {
  30343. if (!this._webGLTexture) {
  30344. return;
  30345. }
  30346. this._references--;
  30347. if (this._references === 0) {
  30348. this._engine._releaseTexture(this);
  30349. this._webGLTexture = null;
  30350. this.previous = null;
  30351. this.next = null;
  30352. }
  30353. };
  30354. /**
  30355. * The source of the texture data is unknown
  30356. */
  30357. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30358. /**
  30359. * Texture data comes from an URL
  30360. */
  30361. InternalTexture.DATASOURCE_URL = 1;
  30362. /**
  30363. * Texture data is only used for temporary storage
  30364. */
  30365. InternalTexture.DATASOURCE_TEMP = 2;
  30366. /**
  30367. * Texture data comes from raw data (ArrayBuffer)
  30368. */
  30369. InternalTexture.DATASOURCE_RAW = 3;
  30370. /**
  30371. * Texture content is dynamic (video or dynamic texture)
  30372. */
  30373. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30374. /**
  30375. * Texture content is generated by rendering to it
  30376. */
  30377. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30378. /**
  30379. * Texture content is part of a multi render target process
  30380. */
  30381. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30382. /**
  30383. * Texture data comes from a cube data file
  30384. */
  30385. InternalTexture.DATASOURCE_CUBE = 7;
  30386. /**
  30387. * Texture data comes from a raw cube data
  30388. */
  30389. InternalTexture.DATASOURCE_CUBERAW = 8;
  30390. /**
  30391. * Texture data come from a prefiltered cube data file
  30392. */
  30393. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30394. /**
  30395. * Texture content is raw 3D data
  30396. */
  30397. InternalTexture.DATASOURCE_RAW3D = 10;
  30398. /**
  30399. * Texture content is a depth texture
  30400. */
  30401. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30402. /**
  30403. * Texture data comes from a raw cube data encoded with RGBD
  30404. */
  30405. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30406. return InternalTexture;
  30407. }());
  30408. BABYLON.InternalTexture = InternalTexture;
  30409. })(BABYLON || (BABYLON = {}));
  30410. //# sourceMappingURL=babylon.internalTexture.js.map
  30411. var BABYLON;
  30412. (function (BABYLON) {
  30413. var BaseTexture = /** @class */ (function () {
  30414. function BaseTexture(scene) {
  30415. this._hasAlpha = false;
  30416. this.getAlphaFromRGB = false;
  30417. this.level = 1;
  30418. this.coordinatesIndex = 0;
  30419. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30420. /**
  30421. * | Value | Type | Description |
  30422. * | ----- | ------------------ | ----------- |
  30423. * | 0 | CLAMP_ADDRESSMODE | |
  30424. * | 1 | WRAP_ADDRESSMODE | |
  30425. * | 2 | MIRROR_ADDRESSMODE | |
  30426. */
  30427. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30428. /**
  30429. * | Value | Type | Description |
  30430. * | ----- | ------------------ | ----------- |
  30431. * | 0 | CLAMP_ADDRESSMODE | |
  30432. * | 1 | WRAP_ADDRESSMODE | |
  30433. * | 2 | MIRROR_ADDRESSMODE | |
  30434. */
  30435. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30436. /**
  30437. * | Value | Type | Description |
  30438. * | ----- | ------------------ | ----------- |
  30439. * | 0 | CLAMP_ADDRESSMODE | |
  30440. * | 1 | WRAP_ADDRESSMODE | |
  30441. * | 2 | MIRROR_ADDRESSMODE | |
  30442. */
  30443. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30444. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30445. this.isCube = false;
  30446. this.is3D = false;
  30447. this.gammaSpace = true;
  30448. this.invertZ = false;
  30449. this.lodLevelInAlpha = false;
  30450. this.isRenderTarget = false;
  30451. this.animations = new Array();
  30452. /**
  30453. * An event triggered when the texture is disposed.
  30454. */
  30455. this.onDisposeObservable = new BABYLON.Observable();
  30456. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30457. this._cachedSize = BABYLON.Size.Zero();
  30458. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30459. if (this._scene) {
  30460. this._scene.textures.push(this);
  30461. }
  30462. this._uid = null;
  30463. }
  30464. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30465. get: function () {
  30466. return this._hasAlpha;
  30467. },
  30468. set: function (value) {
  30469. if (this._hasAlpha === value) {
  30470. return;
  30471. }
  30472. this._hasAlpha = value;
  30473. if (this._scene) {
  30474. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30475. }
  30476. },
  30477. enumerable: true,
  30478. configurable: true
  30479. });
  30480. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30481. get: function () {
  30482. return this._coordinatesMode;
  30483. },
  30484. /**
  30485. * How a texture is mapped.
  30486. *
  30487. * | Value | Type | Description |
  30488. * | ----- | ----------------------------------- | ----------- |
  30489. * | 0 | EXPLICIT_MODE | |
  30490. * | 1 | SPHERICAL_MODE | |
  30491. * | 2 | PLANAR_MODE | |
  30492. * | 3 | CUBIC_MODE | |
  30493. * | 4 | PROJECTION_MODE | |
  30494. * | 5 | SKYBOX_MODE | |
  30495. * | 6 | INVCUBIC_MODE | |
  30496. * | 7 | EQUIRECTANGULAR_MODE | |
  30497. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30498. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30499. */
  30500. set: function (value) {
  30501. if (this._coordinatesMode === value) {
  30502. return;
  30503. }
  30504. this._coordinatesMode = value;
  30505. if (this._scene) {
  30506. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30507. }
  30508. },
  30509. enumerable: true,
  30510. configurable: true
  30511. });
  30512. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30513. /**
  30514. * Gets whether or not the texture contains RGBD data.
  30515. */
  30516. get: function () {
  30517. return this._texture != null && this._texture._isRGBD;
  30518. },
  30519. enumerable: true,
  30520. configurable: true
  30521. });
  30522. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30523. get: function () {
  30524. if (this._texture)
  30525. return this._texture._lodGenerationOffset;
  30526. return 0.0;
  30527. },
  30528. set: function (value) {
  30529. if (this._texture)
  30530. this._texture._lodGenerationOffset = value;
  30531. },
  30532. enumerable: true,
  30533. configurable: true
  30534. });
  30535. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30536. get: function () {
  30537. if (this._texture)
  30538. return this._texture._lodGenerationScale;
  30539. return 0.0;
  30540. },
  30541. set: function (value) {
  30542. if (this._texture)
  30543. this._texture._lodGenerationScale = value;
  30544. },
  30545. enumerable: true,
  30546. configurable: true
  30547. });
  30548. Object.defineProperty(BaseTexture.prototype, "uid", {
  30549. get: function () {
  30550. if (!this._uid) {
  30551. this._uid = BABYLON.Tools.RandomId();
  30552. }
  30553. return this._uid;
  30554. },
  30555. enumerable: true,
  30556. configurable: true
  30557. });
  30558. BaseTexture.prototype.toString = function () {
  30559. return this.name;
  30560. };
  30561. BaseTexture.prototype.getClassName = function () {
  30562. return "BaseTexture";
  30563. };
  30564. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30565. set: function (callback) {
  30566. if (this._onDisposeObserver) {
  30567. this.onDisposeObservable.remove(this._onDisposeObserver);
  30568. }
  30569. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30570. },
  30571. enumerable: true,
  30572. configurable: true
  30573. });
  30574. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30575. get: function () {
  30576. return true;
  30577. },
  30578. enumerable: true,
  30579. configurable: true
  30580. });
  30581. BaseTexture.prototype.getScene = function () {
  30582. return this._scene;
  30583. };
  30584. BaseTexture.prototype.getTextureMatrix = function () {
  30585. return BABYLON.Matrix.IdentityReadOnly;
  30586. };
  30587. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30588. return BABYLON.Matrix.IdentityReadOnly;
  30589. };
  30590. BaseTexture.prototype.getInternalTexture = function () {
  30591. return this._texture;
  30592. };
  30593. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30594. return !this.isBlocking || this.isReady();
  30595. };
  30596. BaseTexture.prototype.isReady = function () {
  30597. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30598. this.delayLoad();
  30599. return false;
  30600. }
  30601. if (this._texture) {
  30602. return this._texture.isReady;
  30603. }
  30604. return false;
  30605. };
  30606. BaseTexture.prototype.getSize = function () {
  30607. if (this._texture) {
  30608. if (this._texture.width) {
  30609. this._cachedSize.width = this._texture.width;
  30610. this._cachedSize.height = this._texture.height;
  30611. return this._cachedSize;
  30612. }
  30613. if (this._texture._size) {
  30614. this._cachedSize.width = this._texture._size;
  30615. this._cachedSize.height = this._texture._size;
  30616. return this._cachedSize;
  30617. }
  30618. }
  30619. return this._cachedSize;
  30620. };
  30621. BaseTexture.prototype.getBaseSize = function () {
  30622. if (!this.isReady() || !this._texture)
  30623. return BABYLON.Size.Zero();
  30624. if (this._texture._size) {
  30625. return new BABYLON.Size(this._texture._size, this._texture._size);
  30626. }
  30627. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30628. };
  30629. BaseTexture.prototype.scale = function (ratio) {
  30630. };
  30631. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30632. get: function () {
  30633. return false;
  30634. },
  30635. enumerable: true,
  30636. configurable: true
  30637. });
  30638. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30639. if (!this._scene) {
  30640. return null;
  30641. }
  30642. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30643. for (var index = 0; index < texturesCache.length; index++) {
  30644. var texturesCacheEntry = texturesCache[index];
  30645. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30646. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30647. texturesCacheEntry.incrementReferences();
  30648. return texturesCacheEntry;
  30649. }
  30650. }
  30651. }
  30652. return null;
  30653. };
  30654. BaseTexture.prototype._rebuild = function () {
  30655. };
  30656. BaseTexture.prototype.delayLoad = function () {
  30657. };
  30658. BaseTexture.prototype.clone = function () {
  30659. return null;
  30660. };
  30661. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30662. get: function () {
  30663. if (!this._texture) {
  30664. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30665. }
  30666. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30667. },
  30668. enumerable: true,
  30669. configurable: true
  30670. });
  30671. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30672. get: function () {
  30673. if (!this._texture) {
  30674. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30675. }
  30676. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30677. },
  30678. enumerable: true,
  30679. configurable: true
  30680. });
  30681. /**
  30682. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30683. * This will returns an RGBA array buffer containing either in values (0-255) or
  30684. * float values (0-1) depending of the underlying buffer type.
  30685. * @param faceIndex The face of the texture to read (in case of cube texture)
  30686. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30687. * @returns The Array buffer containing the pixels data.
  30688. */
  30689. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30690. if (faceIndex === void 0) { faceIndex = 0; }
  30691. if (level === void 0) { level = 0; }
  30692. if (!this._texture) {
  30693. return null;
  30694. }
  30695. var size = this.getSize();
  30696. var width = size.width;
  30697. var height = size.height;
  30698. var scene = this.getScene();
  30699. if (!scene) {
  30700. return null;
  30701. }
  30702. var engine = scene.getEngine();
  30703. if (level != 0) {
  30704. width = width / Math.pow(2, level);
  30705. height = height / Math.pow(2, level);
  30706. width = Math.round(width);
  30707. height = Math.round(height);
  30708. }
  30709. if (this._texture.isCube) {
  30710. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30711. }
  30712. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30713. };
  30714. BaseTexture.prototype.releaseInternalTexture = function () {
  30715. if (this._texture) {
  30716. this._texture.dispose();
  30717. this._texture = null;
  30718. }
  30719. };
  30720. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30721. get: function () {
  30722. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30723. return null;
  30724. }
  30725. if (!this._texture._sphericalPolynomial) {
  30726. this._texture._sphericalPolynomial =
  30727. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30728. }
  30729. return this._texture._sphericalPolynomial;
  30730. },
  30731. set: function (value) {
  30732. if (this._texture) {
  30733. this._texture._sphericalPolynomial = value;
  30734. }
  30735. },
  30736. enumerable: true,
  30737. configurable: true
  30738. });
  30739. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30740. get: function () {
  30741. if (this._texture) {
  30742. return this._texture._lodTextureHigh;
  30743. }
  30744. return null;
  30745. },
  30746. enumerable: true,
  30747. configurable: true
  30748. });
  30749. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30750. get: function () {
  30751. if (this._texture) {
  30752. return this._texture._lodTextureMid;
  30753. }
  30754. return null;
  30755. },
  30756. enumerable: true,
  30757. configurable: true
  30758. });
  30759. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30760. get: function () {
  30761. if (this._texture) {
  30762. return this._texture._lodTextureLow;
  30763. }
  30764. return null;
  30765. },
  30766. enumerable: true,
  30767. configurable: true
  30768. });
  30769. BaseTexture.prototype.dispose = function () {
  30770. if (!this._scene) {
  30771. return;
  30772. }
  30773. // Animations
  30774. this._scene.stopAnimation(this);
  30775. // Remove from scene
  30776. this._scene._removePendingData(this);
  30777. var index = this._scene.textures.indexOf(this);
  30778. if (index >= 0) {
  30779. this._scene.textures.splice(index, 1);
  30780. }
  30781. if (this._texture === undefined) {
  30782. return;
  30783. }
  30784. // Release
  30785. this.releaseInternalTexture();
  30786. // Callback
  30787. this.onDisposeObservable.notifyObservers(this);
  30788. this.onDisposeObservable.clear();
  30789. };
  30790. BaseTexture.prototype.serialize = function () {
  30791. if (!this.name) {
  30792. return null;
  30793. }
  30794. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30795. // Animations
  30796. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30797. return serializationObject;
  30798. };
  30799. BaseTexture.WhenAllReady = function (textures, callback) {
  30800. var numRemaining = textures.length;
  30801. if (numRemaining === 0) {
  30802. callback();
  30803. return;
  30804. }
  30805. var _loop_1 = function () {
  30806. texture = textures[i];
  30807. if (texture.isReady()) {
  30808. if (--numRemaining === 0) {
  30809. callback();
  30810. }
  30811. }
  30812. else {
  30813. onLoadObservable = texture.onLoadObservable;
  30814. var onLoadCallback_1 = function () {
  30815. onLoadObservable.removeCallback(onLoadCallback_1);
  30816. if (--numRemaining === 0) {
  30817. callback();
  30818. }
  30819. };
  30820. onLoadObservable.add(onLoadCallback_1);
  30821. }
  30822. };
  30823. var texture, onLoadObservable;
  30824. for (var i = 0; i < textures.length; i++) {
  30825. _loop_1();
  30826. }
  30827. };
  30828. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30829. __decorate([
  30830. BABYLON.serialize()
  30831. ], BaseTexture.prototype, "name", void 0);
  30832. __decorate([
  30833. BABYLON.serialize("hasAlpha")
  30834. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30835. __decorate([
  30836. BABYLON.serialize()
  30837. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30838. __decorate([
  30839. BABYLON.serialize()
  30840. ], BaseTexture.prototype, "level", void 0);
  30841. __decorate([
  30842. BABYLON.serialize()
  30843. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30844. __decorate([
  30845. BABYLON.serialize("coordinatesMode")
  30846. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30847. __decorate([
  30848. BABYLON.serialize()
  30849. ], BaseTexture.prototype, "wrapU", void 0);
  30850. __decorate([
  30851. BABYLON.serialize()
  30852. ], BaseTexture.prototype, "wrapV", void 0);
  30853. __decorate([
  30854. BABYLON.serialize()
  30855. ], BaseTexture.prototype, "wrapR", void 0);
  30856. __decorate([
  30857. BABYLON.serialize()
  30858. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30859. __decorate([
  30860. BABYLON.serialize()
  30861. ], BaseTexture.prototype, "isCube", void 0);
  30862. __decorate([
  30863. BABYLON.serialize()
  30864. ], BaseTexture.prototype, "is3D", void 0);
  30865. __decorate([
  30866. BABYLON.serialize()
  30867. ], BaseTexture.prototype, "gammaSpace", void 0);
  30868. __decorate([
  30869. BABYLON.serialize()
  30870. ], BaseTexture.prototype, "invertZ", void 0);
  30871. __decorate([
  30872. BABYLON.serialize()
  30873. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30877. __decorate([
  30878. BABYLON.serialize()
  30879. ], BaseTexture.prototype, "lodGenerationScale", null);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30883. return BaseTexture;
  30884. }());
  30885. BABYLON.BaseTexture = BaseTexture;
  30886. })(BABYLON || (BABYLON = {}));
  30887. //# sourceMappingURL=babylon.baseTexture.js.map
  30888. var BABYLON;
  30889. (function (BABYLON) {
  30890. var Texture = /** @class */ (function (_super) {
  30891. __extends(Texture, _super);
  30892. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30893. if (noMipmap === void 0) { noMipmap = false; }
  30894. if (invertY === void 0) { invertY = true; }
  30895. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30896. if (onLoad === void 0) { onLoad = null; }
  30897. if (onError === void 0) { onError = null; }
  30898. if (buffer === void 0) { buffer = null; }
  30899. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30900. var _this = _super.call(this, scene) || this;
  30901. _this.uOffset = 0;
  30902. _this.vOffset = 0;
  30903. _this.uScale = 1.0;
  30904. _this.vScale = 1.0;
  30905. _this.uAng = 0;
  30906. _this.vAng = 0;
  30907. _this.wAng = 0;
  30908. /**
  30909. * Defines the center of rotation (U)
  30910. */
  30911. _this.uRotationCenter = 0.5;
  30912. /**
  30913. * Defines the center of rotation (V)
  30914. */
  30915. _this.vRotationCenter = 0.5;
  30916. /**
  30917. * Defines the center of rotation (W)
  30918. */
  30919. _this.wRotationCenter = 0.5;
  30920. _this._isBlocking = true;
  30921. _this.name = url || "";
  30922. _this.url = url;
  30923. _this._noMipmap = noMipmap;
  30924. _this._invertY = invertY;
  30925. _this._samplingMode = samplingMode;
  30926. _this._buffer = buffer;
  30927. _this._deleteBuffer = deleteBuffer;
  30928. if (format) {
  30929. _this._format = format;
  30930. }
  30931. scene = _this.getScene();
  30932. if (!scene) {
  30933. return _this;
  30934. }
  30935. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30936. var load = function () {
  30937. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30938. _this.onLoadObservable.notifyObservers(_this);
  30939. }
  30940. if (onLoad) {
  30941. onLoad();
  30942. }
  30943. if (!_this.isBlocking && scene) {
  30944. scene.resetCachedMaterial();
  30945. }
  30946. };
  30947. if (!_this.url) {
  30948. _this._delayedOnLoad = load;
  30949. _this._delayedOnError = onError;
  30950. return _this;
  30951. }
  30952. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30953. if (!_this._texture) {
  30954. if (!scene.useDelayedTextureLoading) {
  30955. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30956. if (deleteBuffer) {
  30957. delete _this._buffer;
  30958. }
  30959. }
  30960. else {
  30961. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30962. _this._delayedOnLoad = load;
  30963. _this._delayedOnError = onError;
  30964. }
  30965. }
  30966. else {
  30967. if (_this._texture.isReady) {
  30968. BABYLON.Tools.SetImmediate(function () { return load(); });
  30969. }
  30970. else {
  30971. _this._texture.onLoadedObservable.add(load);
  30972. }
  30973. }
  30974. return _this;
  30975. }
  30976. Object.defineProperty(Texture.prototype, "noMipmap", {
  30977. get: function () {
  30978. return this._noMipmap;
  30979. },
  30980. enumerable: true,
  30981. configurable: true
  30982. });
  30983. Object.defineProperty(Texture.prototype, "isBlocking", {
  30984. get: function () {
  30985. return this._isBlocking;
  30986. },
  30987. set: function (value) {
  30988. this._isBlocking = value;
  30989. },
  30990. enumerable: true,
  30991. configurable: true
  30992. });
  30993. Object.defineProperty(Texture.prototype, "samplingMode", {
  30994. get: function () {
  30995. return this._samplingMode;
  30996. },
  30997. enumerable: true,
  30998. configurable: true
  30999. });
  31000. /**
  31001. * Update the url (and optional buffer) of this texture if url was null during construction.
  31002. * @param url the url of the texture
  31003. * @param buffer the buffer of the texture (defaults to null)
  31004. */
  31005. Texture.prototype.updateURL = function (url, buffer) {
  31006. if (buffer === void 0) { buffer = null; }
  31007. if (this.url) {
  31008. throw new Error("URL is already set");
  31009. }
  31010. this.url = url;
  31011. this._buffer = buffer;
  31012. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31013. this.delayLoad();
  31014. };
  31015. Texture.prototype.delayLoad = function () {
  31016. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31017. return;
  31018. }
  31019. var scene = this.getScene();
  31020. if (!scene) {
  31021. return;
  31022. }
  31023. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31024. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31025. if (!this._texture) {
  31026. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31027. if (this._deleteBuffer) {
  31028. delete this._buffer;
  31029. }
  31030. }
  31031. else {
  31032. if (this._delayedOnLoad) {
  31033. if (this._texture.isReady) {
  31034. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31035. }
  31036. else {
  31037. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31038. }
  31039. }
  31040. }
  31041. this._delayedOnLoad = null;
  31042. this._delayedOnError = null;
  31043. };
  31044. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31045. if (!this._texture) {
  31046. return;
  31047. }
  31048. var scene = this.getScene();
  31049. if (!scene) {
  31050. return;
  31051. }
  31052. this._samplingMode = samplingMode;
  31053. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31054. };
  31055. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31056. x *= this.uScale;
  31057. y *= this.vScale;
  31058. x -= this.uRotationCenter * this.uScale;
  31059. y -= this.vRotationCenter * this.vScale;
  31060. z -= this.wRotationCenter;
  31061. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31062. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31063. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31064. t.z += this.wRotationCenter;
  31065. };
  31066. Texture.prototype.getTextureMatrix = function () {
  31067. var _this = this;
  31068. if (this.uOffset === this._cachedUOffset &&
  31069. this.vOffset === this._cachedVOffset &&
  31070. this.uScale === this._cachedUScale &&
  31071. this.vScale === this._cachedVScale &&
  31072. this.uAng === this._cachedUAng &&
  31073. this.vAng === this._cachedVAng &&
  31074. this.wAng === this._cachedWAng) {
  31075. return this._cachedTextureMatrix;
  31076. }
  31077. this._cachedUOffset = this.uOffset;
  31078. this._cachedVOffset = this.vOffset;
  31079. this._cachedUScale = this.uScale;
  31080. this._cachedVScale = this.vScale;
  31081. this._cachedUAng = this.uAng;
  31082. this._cachedVAng = this.vAng;
  31083. this._cachedWAng = this.wAng;
  31084. if (!this._cachedTextureMatrix) {
  31085. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31086. this._rowGenerationMatrix = new BABYLON.Matrix();
  31087. this._t0 = BABYLON.Vector3.Zero();
  31088. this._t1 = BABYLON.Vector3.Zero();
  31089. this._t2 = BABYLON.Vector3.Zero();
  31090. }
  31091. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31092. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31093. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31094. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31095. this._t1.subtractInPlace(this._t0);
  31096. this._t2.subtractInPlace(this._t0);
  31097. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31098. this._cachedTextureMatrix.m[0] = this._t1.x;
  31099. this._cachedTextureMatrix.m[1] = this._t1.y;
  31100. this._cachedTextureMatrix.m[2] = this._t1.z;
  31101. this._cachedTextureMatrix.m[4] = this._t2.x;
  31102. this._cachedTextureMatrix.m[5] = this._t2.y;
  31103. this._cachedTextureMatrix.m[6] = this._t2.z;
  31104. this._cachedTextureMatrix.m[8] = this._t0.x;
  31105. this._cachedTextureMatrix.m[9] = this._t0.y;
  31106. this._cachedTextureMatrix.m[10] = this._t0.z;
  31107. var scene = this.getScene();
  31108. if (!scene) {
  31109. return this._cachedTextureMatrix;
  31110. }
  31111. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31112. return mat.hasTexture(_this);
  31113. });
  31114. return this._cachedTextureMatrix;
  31115. };
  31116. Texture.prototype.getReflectionTextureMatrix = function () {
  31117. var _this = this;
  31118. var scene = this.getScene();
  31119. if (!scene) {
  31120. return this._cachedTextureMatrix;
  31121. }
  31122. if (this.uOffset === this._cachedUOffset &&
  31123. this.vOffset === this._cachedVOffset &&
  31124. this.uScale === this._cachedUScale &&
  31125. this.vScale === this._cachedVScale &&
  31126. this.coordinatesMode === this._cachedCoordinatesMode) {
  31127. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31128. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31129. return this._cachedTextureMatrix;
  31130. }
  31131. }
  31132. else {
  31133. return this._cachedTextureMatrix;
  31134. }
  31135. }
  31136. if (!this._cachedTextureMatrix) {
  31137. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31138. }
  31139. if (!this._projectionModeMatrix) {
  31140. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31141. }
  31142. this._cachedUOffset = this.uOffset;
  31143. this._cachedVOffset = this.vOffset;
  31144. this._cachedUScale = this.uScale;
  31145. this._cachedVScale = this.vScale;
  31146. this._cachedCoordinatesMode = this.coordinatesMode;
  31147. switch (this.coordinatesMode) {
  31148. case Texture.PLANAR_MODE:
  31149. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31150. this._cachedTextureMatrix[0] = this.uScale;
  31151. this._cachedTextureMatrix[5] = this.vScale;
  31152. this._cachedTextureMatrix[12] = this.uOffset;
  31153. this._cachedTextureMatrix[13] = this.vOffset;
  31154. break;
  31155. case Texture.PROJECTION_MODE:
  31156. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31157. this._projectionModeMatrix.m[0] = 0.5;
  31158. this._projectionModeMatrix.m[5] = -0.5;
  31159. this._projectionModeMatrix.m[10] = 0.0;
  31160. this._projectionModeMatrix.m[12] = 0.5;
  31161. this._projectionModeMatrix.m[13] = 0.5;
  31162. this._projectionModeMatrix.m[14] = 1.0;
  31163. this._projectionModeMatrix.m[15] = 1.0;
  31164. var projectionMatrix = scene.getProjectionMatrix();
  31165. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31166. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31167. break;
  31168. default:
  31169. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31170. break;
  31171. }
  31172. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31173. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31174. });
  31175. return this._cachedTextureMatrix;
  31176. };
  31177. Texture.prototype.clone = function () {
  31178. var _this = this;
  31179. return BABYLON.SerializationHelper.Clone(function () {
  31180. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31181. }, this);
  31182. };
  31183. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31184. get: function () {
  31185. if (!this._onLoadObservable) {
  31186. this._onLoadObservable = new BABYLON.Observable();
  31187. }
  31188. return this._onLoadObservable;
  31189. },
  31190. enumerable: true,
  31191. configurable: true
  31192. });
  31193. Texture.prototype.serialize = function () {
  31194. var serializationObject = _super.prototype.serialize.call(this);
  31195. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31196. serializationObject.base64String = this._buffer;
  31197. serializationObject.name = serializationObject.name.replace("data:", "");
  31198. }
  31199. serializationObject.invertY = this._invertY;
  31200. serializationObject.samplingMode = this.samplingMode;
  31201. return serializationObject;
  31202. };
  31203. Texture.prototype.getClassName = function () {
  31204. return "Texture";
  31205. };
  31206. Texture.prototype.dispose = function () {
  31207. _super.prototype.dispose.call(this);
  31208. if (this._onLoadObservable) {
  31209. this._onLoadObservable.clear();
  31210. this._onLoadObservable = null;
  31211. }
  31212. this._delayedOnLoad = null;
  31213. this._delayedOnError = null;
  31214. };
  31215. // Statics
  31216. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31217. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31218. if (onLoad === void 0) { onLoad = null; }
  31219. if (onError === void 0) { onError = null; }
  31220. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31221. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31222. };
  31223. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31224. if (parsedTexture.customType) {
  31225. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31226. // Update Sampling Mode
  31227. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31228. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31229. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31230. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31231. }
  31232. }
  31233. return parsedCustomTexture;
  31234. }
  31235. if (parsedTexture.isCube) {
  31236. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31237. }
  31238. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31239. return null;
  31240. }
  31241. var texture = BABYLON.SerializationHelper.Parse(function () {
  31242. var generateMipMaps = true;
  31243. if (parsedTexture.noMipmap) {
  31244. generateMipMaps = false;
  31245. }
  31246. if (parsedTexture.mirrorPlane) {
  31247. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31248. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31249. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31250. return mirrorTexture;
  31251. }
  31252. else if (parsedTexture.isRenderTarget) {
  31253. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31254. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31255. return renderTargetTexture;
  31256. }
  31257. else {
  31258. var texture;
  31259. if (parsedTexture.base64String) {
  31260. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31261. }
  31262. else {
  31263. var url = rootUrl + parsedTexture.name;
  31264. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31265. url = parsedTexture.url;
  31266. }
  31267. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31268. }
  31269. return texture;
  31270. }
  31271. }, parsedTexture, scene);
  31272. // Update Sampling Mode
  31273. if (parsedTexture.samplingMode) {
  31274. var sampling = parsedTexture.samplingMode;
  31275. if (texture._samplingMode !== sampling) {
  31276. texture.updateSamplingMode(sampling);
  31277. }
  31278. }
  31279. // Animations
  31280. if (parsedTexture.animations) {
  31281. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31282. var parsedAnimation = parsedTexture.animations[animationIndex];
  31283. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31284. }
  31285. }
  31286. return texture;
  31287. };
  31288. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31289. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31290. if (noMipmap === void 0) { noMipmap = false; }
  31291. if (invertY === void 0) { invertY = true; }
  31292. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31293. if (onLoad === void 0) { onLoad = null; }
  31294. if (onError === void 0) { onError = null; }
  31295. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31296. if (name.substr(0, 5) !== "data:") {
  31297. name = "data:" + name;
  31298. }
  31299. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31300. };
  31301. // Constants
  31302. Texture.NEAREST_SAMPLINGMODE = 1;
  31303. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31304. Texture.BILINEAR_SAMPLINGMODE = 2;
  31305. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31306. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31307. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31308. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31309. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31310. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31311. Texture.NEAREST_LINEAR = 7;
  31312. Texture.NEAREST_NEAREST = 8;
  31313. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31314. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31315. Texture.LINEAR_LINEAR = 11;
  31316. Texture.LINEAR_NEAREST = 12;
  31317. Texture.EXPLICIT_MODE = 0;
  31318. Texture.SPHERICAL_MODE = 1;
  31319. Texture.PLANAR_MODE = 2;
  31320. Texture.CUBIC_MODE = 3;
  31321. Texture.PROJECTION_MODE = 4;
  31322. Texture.SKYBOX_MODE = 5;
  31323. Texture.INVCUBIC_MODE = 6;
  31324. Texture.EQUIRECTANGULAR_MODE = 7;
  31325. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31326. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31327. Texture.CLAMP_ADDRESSMODE = 0;
  31328. Texture.WRAP_ADDRESSMODE = 1;
  31329. Texture.MIRROR_ADDRESSMODE = 2;
  31330. /**
  31331. * 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
  31332. */
  31333. Texture.UseSerializedUrlIfAny = false;
  31334. __decorate([
  31335. BABYLON.serialize()
  31336. ], Texture.prototype, "url", void 0);
  31337. __decorate([
  31338. BABYLON.serialize()
  31339. ], Texture.prototype, "uOffset", void 0);
  31340. __decorate([
  31341. BABYLON.serialize()
  31342. ], Texture.prototype, "vOffset", void 0);
  31343. __decorate([
  31344. BABYLON.serialize()
  31345. ], Texture.prototype, "uScale", void 0);
  31346. __decorate([
  31347. BABYLON.serialize()
  31348. ], Texture.prototype, "vScale", void 0);
  31349. __decorate([
  31350. BABYLON.serialize()
  31351. ], Texture.prototype, "uAng", void 0);
  31352. __decorate([
  31353. BABYLON.serialize()
  31354. ], Texture.prototype, "vAng", void 0);
  31355. __decorate([
  31356. BABYLON.serialize()
  31357. ], Texture.prototype, "wAng", void 0);
  31358. __decorate([
  31359. BABYLON.serialize()
  31360. ], Texture.prototype, "uRotationCenter", void 0);
  31361. __decorate([
  31362. BABYLON.serialize()
  31363. ], Texture.prototype, "vRotationCenter", void 0);
  31364. __decorate([
  31365. BABYLON.serialize()
  31366. ], Texture.prototype, "wRotationCenter", void 0);
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], Texture.prototype, "isBlocking", null);
  31370. return Texture;
  31371. }(BABYLON.BaseTexture));
  31372. BABYLON.Texture = Texture;
  31373. })(BABYLON || (BABYLON = {}));
  31374. //# sourceMappingURL=babylon.texture.js.map
  31375. var BABYLON;
  31376. (function (BABYLON) {
  31377. /**
  31378. * @hidden
  31379. **/
  31380. var _InstancesBatch = /** @class */ (function () {
  31381. function _InstancesBatch() {
  31382. this.mustReturn = false;
  31383. this.visibleInstances = new Array();
  31384. this.renderSelf = new Array();
  31385. }
  31386. return _InstancesBatch;
  31387. }());
  31388. BABYLON._InstancesBatch = _InstancesBatch;
  31389. var Mesh = /** @class */ (function (_super) {
  31390. __extends(Mesh, _super);
  31391. /**
  31392. * @constructor
  31393. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31394. * @param {Scene} scene The scene to add this mesh to.
  31395. * @param {Node} parent The parent of this mesh, if it has one
  31396. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31397. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31398. * When false, achieved by calling a clone(), also passing False.
  31399. * This will make creation of children, recursive.
  31400. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31401. */
  31402. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31403. if (scene === void 0) { scene = null; }
  31404. if (parent === void 0) { parent = null; }
  31405. if (source === void 0) { source = null; }
  31406. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31407. var _this = _super.call(this, name, scene) || this;
  31408. // Events
  31409. /**
  31410. * An event triggered before rendering the mesh
  31411. */
  31412. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31413. /**
  31414. * An event triggered after rendering the mesh
  31415. */
  31416. _this.onAfterRenderObservable = new BABYLON.Observable();
  31417. /**
  31418. * An event triggered before drawing the mesh
  31419. */
  31420. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31421. // Members
  31422. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31423. _this.instances = new Array();
  31424. _this._LODLevels = new Array();
  31425. _this._visibleInstances = {};
  31426. _this._renderIdForInstances = new Array();
  31427. _this._batchCache = new _InstancesBatch();
  31428. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31429. // Use by builder only to know what orientation were the mesh build in.
  31430. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31431. _this.overrideMaterialSideOrientation = null;
  31432. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31433. // Will be used to save a source mesh reference, If any
  31434. _this._source = null;
  31435. scene = _this.getScene();
  31436. if (source) {
  31437. // Geometry
  31438. if (source._geometry) {
  31439. source._geometry.applyToMesh(_this);
  31440. }
  31441. // Deep copy
  31442. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31443. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31444. // Source mesh
  31445. _this._source = source;
  31446. // Metadata
  31447. if (source.metadata && source.metadata.clone) {
  31448. _this.metadata = source.metadata.clone();
  31449. }
  31450. else {
  31451. _this.metadata = source.metadata;
  31452. }
  31453. // Tags
  31454. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31455. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31456. }
  31457. // Parent
  31458. _this.parent = source.parent;
  31459. // Pivot
  31460. _this.setPivotMatrix(source.getPivotMatrix());
  31461. _this.id = name + "." + source.id;
  31462. // Material
  31463. _this.material = source.material;
  31464. var index;
  31465. if (!doNotCloneChildren) {
  31466. // Children
  31467. var directDescendants = source.getDescendants(true);
  31468. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31469. var child = directDescendants[index_1];
  31470. if (child.clone) {
  31471. child.clone(name + "." + child.name, _this);
  31472. }
  31473. }
  31474. }
  31475. // Physics clone
  31476. var physicsEngine = _this.getScene().getPhysicsEngine();
  31477. if (clonePhysicsImpostor && physicsEngine) {
  31478. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31479. if (impostor) {
  31480. _this.physicsImpostor = impostor.clone(_this);
  31481. }
  31482. }
  31483. // Particles
  31484. for (index = 0; index < scene.particleSystems.length; index++) {
  31485. var system = scene.particleSystems[index];
  31486. if (system.emitter === source) {
  31487. system.clone(system.name, _this);
  31488. }
  31489. }
  31490. _this.refreshBoundingInfo();
  31491. _this.computeWorldMatrix(true);
  31492. }
  31493. // Parent
  31494. if (parent !== null) {
  31495. _this.parent = parent;
  31496. }
  31497. return _this;
  31498. }
  31499. Object.defineProperty(Mesh, "FRONTSIDE", {
  31500. /**
  31501. * Mesh side orientation : usually the external or front surface
  31502. */
  31503. get: function () {
  31504. return Mesh._FRONTSIDE;
  31505. },
  31506. enumerable: true,
  31507. configurable: true
  31508. });
  31509. Object.defineProperty(Mesh, "BACKSIDE", {
  31510. /**
  31511. * Mesh side orientation : usually the internal or back surface
  31512. */
  31513. get: function () {
  31514. return Mesh._BACKSIDE;
  31515. },
  31516. enumerable: true,
  31517. configurable: true
  31518. });
  31519. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31520. /**
  31521. * Mesh side orientation : both internal and external or front and back surfaces
  31522. */
  31523. get: function () {
  31524. return Mesh._DOUBLESIDE;
  31525. },
  31526. enumerable: true,
  31527. configurable: true
  31528. });
  31529. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31530. /**
  31531. * Mesh side orientation : by default, `FRONTSIDE`
  31532. */
  31533. get: function () {
  31534. return Mesh._DEFAULTSIDE;
  31535. },
  31536. enumerable: true,
  31537. configurable: true
  31538. });
  31539. Object.defineProperty(Mesh, "NO_CAP", {
  31540. /**
  31541. * Mesh cap setting : no cap
  31542. */
  31543. get: function () {
  31544. return Mesh._NO_CAP;
  31545. },
  31546. enumerable: true,
  31547. configurable: true
  31548. });
  31549. Object.defineProperty(Mesh, "CAP_START", {
  31550. /**
  31551. * Mesh cap setting : one cap at the beginning of the mesh
  31552. */
  31553. get: function () {
  31554. return Mesh._CAP_START;
  31555. },
  31556. enumerable: true,
  31557. configurable: true
  31558. });
  31559. Object.defineProperty(Mesh, "CAP_END", {
  31560. /**
  31561. * Mesh cap setting : one cap at the end of the mesh
  31562. */
  31563. get: function () {
  31564. return Mesh._CAP_END;
  31565. },
  31566. enumerable: true,
  31567. configurable: true
  31568. });
  31569. Object.defineProperty(Mesh, "CAP_ALL", {
  31570. /**
  31571. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31572. */
  31573. get: function () {
  31574. return Mesh._CAP_ALL;
  31575. },
  31576. enumerable: true,
  31577. configurable: true
  31578. });
  31579. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31580. set: function (callback) {
  31581. if (this._onBeforeDrawObserver) {
  31582. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31583. }
  31584. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31585. },
  31586. enumerable: true,
  31587. configurable: true
  31588. });
  31589. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31590. get: function () {
  31591. return this._morphTargetManager;
  31592. },
  31593. set: function (value) {
  31594. if (this._morphTargetManager === value) {
  31595. return;
  31596. }
  31597. this._morphTargetManager = value;
  31598. this._syncGeometryWithMorphTargetManager();
  31599. },
  31600. enumerable: true,
  31601. configurable: true
  31602. });
  31603. Object.defineProperty(Mesh.prototype, "source", {
  31604. get: function () {
  31605. return this._source;
  31606. },
  31607. enumerable: true,
  31608. configurable: true
  31609. });
  31610. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31611. get: function () {
  31612. return this._unIndexed;
  31613. },
  31614. set: function (value) {
  31615. if (this._unIndexed !== value) {
  31616. this._unIndexed = value;
  31617. this._markSubMeshesAsAttributesDirty();
  31618. }
  31619. },
  31620. enumerable: true,
  31621. configurable: true
  31622. });
  31623. // Methods
  31624. /**
  31625. * Returns the string "Mesh".
  31626. */
  31627. Mesh.prototype.getClassName = function () {
  31628. return "Mesh";
  31629. };
  31630. /**
  31631. * Returns a string.
  31632. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31633. */
  31634. Mesh.prototype.toString = function (fullDetails) {
  31635. var ret = _super.prototype.toString.call(this, fullDetails);
  31636. ret += ", n vertices: " + this.getTotalVertices();
  31637. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31638. if (this.animations) {
  31639. for (var i = 0; i < this.animations.length; i++) {
  31640. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31641. }
  31642. }
  31643. if (fullDetails) {
  31644. if (this._geometry) {
  31645. var ib = this.getIndices();
  31646. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31647. if (vb && ib) {
  31648. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31649. }
  31650. }
  31651. else {
  31652. ret += ", flat shading: UNKNOWN";
  31653. }
  31654. }
  31655. return ret;
  31656. };
  31657. Mesh.prototype._unBindEffect = function () {
  31658. _super.prototype._unBindEffect.call(this);
  31659. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31660. var instance = _a[_i];
  31661. instance._unBindEffect();
  31662. }
  31663. };
  31664. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31665. /**
  31666. * True if the mesh has some Levels Of Details (LOD).
  31667. * Returns a boolean.
  31668. */
  31669. get: function () {
  31670. return this._LODLevels.length > 0;
  31671. },
  31672. enumerable: true,
  31673. configurable: true
  31674. });
  31675. /**
  31676. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31677. * @returns an array of {BABYLON.MeshLODLevel}
  31678. */
  31679. Mesh.prototype.getLODLevels = function () {
  31680. return this._LODLevels;
  31681. };
  31682. Mesh.prototype._sortLODLevels = function () {
  31683. this._LODLevels.sort(function (a, b) {
  31684. if (a.distance < b.distance) {
  31685. return 1;
  31686. }
  31687. if (a.distance > b.distance) {
  31688. return -1;
  31689. }
  31690. return 0;
  31691. });
  31692. };
  31693. /**
  31694. * Add a mesh as LOD level triggered at the given distance.
  31695. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31696. * @param distance The distance from the center of the object to show this level
  31697. * @param mesh The mesh to be added as LOD level (can be null)
  31698. * @return This mesh (for chaining)
  31699. */
  31700. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31701. if (mesh && mesh._masterMesh) {
  31702. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31703. return this;
  31704. }
  31705. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31706. this._LODLevels.push(level);
  31707. if (mesh) {
  31708. mesh._masterMesh = this;
  31709. }
  31710. this._sortLODLevels();
  31711. return this;
  31712. };
  31713. /**
  31714. * Returns the LOD level mesh at the passed distance or null if not found.
  31715. * It is related to the method `addLODLevel(distance, mesh)`.
  31716. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31717. * Returns an object Mesh or `null`.
  31718. */
  31719. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31720. for (var index = 0; index < this._LODLevels.length; index++) {
  31721. var level = this._LODLevels[index];
  31722. if (level.distance === distance) {
  31723. return level.mesh;
  31724. }
  31725. }
  31726. return null;
  31727. };
  31728. /**
  31729. * Remove a mesh from the LOD array
  31730. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31731. * @param {Mesh} mesh The mesh to be removed.
  31732. * @return {Mesh} This mesh (for chaining)
  31733. */
  31734. Mesh.prototype.removeLODLevel = function (mesh) {
  31735. for (var index = 0; index < this._LODLevels.length; index++) {
  31736. if (this._LODLevels[index].mesh === mesh) {
  31737. this._LODLevels.splice(index, 1);
  31738. if (mesh) {
  31739. mesh._masterMesh = null;
  31740. }
  31741. }
  31742. }
  31743. this._sortLODLevels();
  31744. return this;
  31745. };
  31746. /**
  31747. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31748. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31749. */
  31750. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31751. if (!this._LODLevels || this._LODLevels.length === 0) {
  31752. return this;
  31753. }
  31754. var bSphere;
  31755. if (boundingSphere) {
  31756. bSphere = boundingSphere;
  31757. }
  31758. else {
  31759. var boundingInfo = this.getBoundingInfo();
  31760. bSphere = boundingInfo.boundingSphere;
  31761. }
  31762. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31763. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31764. if (this.onLODLevelSelection) {
  31765. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31766. }
  31767. return this;
  31768. }
  31769. for (var index = 0; index < this._LODLevels.length; index++) {
  31770. var level = this._LODLevels[index];
  31771. if (level.distance < distanceToCamera) {
  31772. if (level.mesh) {
  31773. level.mesh._preActivate();
  31774. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31775. }
  31776. if (this.onLODLevelSelection) {
  31777. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31778. }
  31779. return level.mesh;
  31780. }
  31781. }
  31782. if (this.onLODLevelSelection) {
  31783. this.onLODLevelSelection(distanceToCamera, this, this);
  31784. }
  31785. return this;
  31786. };
  31787. Object.defineProperty(Mesh.prototype, "geometry", {
  31788. /**
  31789. * Returns the mesh internal Geometry object.
  31790. */
  31791. get: function () {
  31792. return this._geometry;
  31793. },
  31794. enumerable: true,
  31795. configurable: true
  31796. });
  31797. /**
  31798. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31799. */
  31800. Mesh.prototype.getTotalVertices = function () {
  31801. if (this._geometry === null || this._geometry === undefined) {
  31802. return 0;
  31803. }
  31804. return this._geometry.getTotalVertices();
  31805. };
  31806. /**
  31807. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31808. * 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.
  31809. * You can force the copy with forceCopy === true
  31810. * Returns null if the mesh has no geometry or no vertex buffer.
  31811. * Possible `kind` values :
  31812. * - BABYLON.VertexBuffer.PositionKind
  31813. * - BABYLON.VertexBuffer.UVKind
  31814. * - BABYLON.VertexBuffer.UV2Kind
  31815. * - BABYLON.VertexBuffer.UV3Kind
  31816. * - BABYLON.VertexBuffer.UV4Kind
  31817. * - BABYLON.VertexBuffer.UV5Kind
  31818. * - BABYLON.VertexBuffer.UV6Kind
  31819. * - BABYLON.VertexBuffer.ColorKind
  31820. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31821. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31822. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31823. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31824. */
  31825. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31826. if (!this._geometry) {
  31827. return null;
  31828. }
  31829. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31830. };
  31831. /**
  31832. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31833. * Returns `null` if the mesh has no geometry.
  31834. * Possible `kind` values :
  31835. * - BABYLON.VertexBuffer.PositionKind
  31836. * - BABYLON.VertexBuffer.UVKind
  31837. * - BABYLON.VertexBuffer.UV2Kind
  31838. * - BABYLON.VertexBuffer.UV3Kind
  31839. * - BABYLON.VertexBuffer.UV4Kind
  31840. * - BABYLON.VertexBuffer.UV5Kind
  31841. * - BABYLON.VertexBuffer.UV6Kind
  31842. * - BABYLON.VertexBuffer.ColorKind
  31843. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31844. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31845. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31846. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31847. */
  31848. Mesh.prototype.getVertexBuffer = function (kind) {
  31849. if (!this._geometry) {
  31850. return null;
  31851. }
  31852. return this._geometry.getVertexBuffer(kind);
  31853. };
  31854. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31855. if (!this._geometry) {
  31856. if (this._delayInfo) {
  31857. return this._delayInfo.indexOf(kind) !== -1;
  31858. }
  31859. return false;
  31860. }
  31861. return this._geometry.isVerticesDataPresent(kind);
  31862. };
  31863. /**
  31864. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31865. * Possible `kind` values :
  31866. * - BABYLON.VertexBuffer.PositionKind
  31867. * - BABYLON.VertexBuffer.UVKind
  31868. * - BABYLON.VertexBuffer.UV2Kind
  31869. * - BABYLON.VertexBuffer.UV3Kind
  31870. * - BABYLON.VertexBuffer.UV4Kind
  31871. * - BABYLON.VertexBuffer.UV5Kind
  31872. * - BABYLON.VertexBuffer.UV6Kind
  31873. * - BABYLON.VertexBuffer.ColorKind
  31874. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31875. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31876. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31877. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31878. */
  31879. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31880. if (!this._geometry) {
  31881. if (this._delayInfo) {
  31882. return this._delayInfo.indexOf(kind) !== -1;
  31883. }
  31884. return false;
  31885. }
  31886. return this._geometry.isVertexBufferUpdatable(kind);
  31887. };
  31888. /**
  31889. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31890. * Possible `kind` values :
  31891. * - BABYLON.VertexBuffer.PositionKind
  31892. * - BABYLON.VertexBuffer.UVKind
  31893. * - BABYLON.VertexBuffer.UV2Kind
  31894. * - BABYLON.VertexBuffer.UV3Kind
  31895. * - BABYLON.VertexBuffer.UV4Kind
  31896. * - BABYLON.VertexBuffer.UV5Kind
  31897. * - BABYLON.VertexBuffer.UV6Kind
  31898. * - BABYLON.VertexBuffer.ColorKind
  31899. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31900. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31901. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31902. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31903. */
  31904. Mesh.prototype.getVerticesDataKinds = function () {
  31905. if (!this._geometry) {
  31906. var result = new Array();
  31907. if (this._delayInfo) {
  31908. this._delayInfo.forEach(function (kind, index, array) {
  31909. result.push(kind);
  31910. });
  31911. }
  31912. return result;
  31913. }
  31914. return this._geometry.getVerticesDataKinds();
  31915. };
  31916. /**
  31917. * Returns a positive integer : the total number of indices in this mesh geometry.
  31918. * Returns zero if the mesh has no geometry.
  31919. */
  31920. Mesh.prototype.getTotalIndices = function () {
  31921. if (!this._geometry) {
  31922. return 0;
  31923. }
  31924. return this._geometry.getTotalIndices();
  31925. };
  31926. /**
  31927. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31928. * 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.
  31929. * Returns an empty array if the mesh has no geometry.
  31930. */
  31931. Mesh.prototype.getIndices = function (copyWhenShared) {
  31932. if (!this._geometry) {
  31933. return [];
  31934. }
  31935. return this._geometry.getIndices(copyWhenShared);
  31936. };
  31937. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31938. get: function () {
  31939. return this._masterMesh !== null && this._masterMesh !== undefined;
  31940. },
  31941. enumerable: true,
  31942. configurable: true
  31943. });
  31944. /**
  31945. * Determine if the current mesh is ready to be rendered
  31946. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31947. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31948. * @returns true if all associated assets are ready (material, textures, shaders)
  31949. */
  31950. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31951. if (completeCheck === void 0) { completeCheck = false; }
  31952. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31953. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31954. return false;
  31955. }
  31956. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31957. return false;
  31958. }
  31959. if (!this.subMeshes || this.subMeshes.length === 0) {
  31960. return true;
  31961. }
  31962. if (!completeCheck) {
  31963. return true;
  31964. }
  31965. var engine = this.getEngine();
  31966. var scene = this.getScene();
  31967. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31968. this.computeWorldMatrix();
  31969. var mat = this.material || scene.defaultMaterial;
  31970. if (mat) {
  31971. if (mat.storeEffectOnSubMeshes) {
  31972. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31973. var subMesh = _a[_i];
  31974. var effectiveMaterial = subMesh.getMaterial();
  31975. if (effectiveMaterial) {
  31976. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31977. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31978. return false;
  31979. }
  31980. }
  31981. else {
  31982. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31983. return false;
  31984. }
  31985. }
  31986. }
  31987. }
  31988. }
  31989. else {
  31990. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31991. return false;
  31992. }
  31993. }
  31994. }
  31995. // Shadows
  31996. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31997. var light = _c[_b];
  31998. var generator = light.getShadowGenerator();
  31999. if (generator) {
  32000. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32001. var subMesh = _e[_d];
  32002. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32003. return false;
  32004. }
  32005. }
  32006. }
  32007. }
  32008. // LOD
  32009. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32010. var lod = _g[_f];
  32011. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32012. return false;
  32013. }
  32014. }
  32015. return true;
  32016. };
  32017. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32018. /**
  32019. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32020. * This property is pertinent only for updatable parametric shapes.
  32021. */
  32022. get: function () {
  32023. return this._areNormalsFrozen;
  32024. },
  32025. enumerable: true,
  32026. configurable: true
  32027. });
  32028. /**
  32029. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32030. * It has no effect at all on other shapes.
  32031. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32032. * Returns the Mesh.
  32033. */
  32034. Mesh.prototype.freezeNormals = function () {
  32035. this._areNormalsFrozen = true;
  32036. return this;
  32037. };
  32038. /**
  32039. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32040. * It has no effect at all on other shapes.
  32041. * It reactivates the mesh normals computation if it was previously frozen.
  32042. * Returns the Mesh.
  32043. */
  32044. Mesh.prototype.unfreezeNormals = function () {
  32045. this._areNormalsFrozen = false;
  32046. return this;
  32047. };
  32048. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32049. /**
  32050. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32051. */
  32052. set: function (count) {
  32053. this._overridenInstanceCount = count;
  32054. },
  32055. enumerable: true,
  32056. configurable: true
  32057. });
  32058. // Methods
  32059. Mesh.prototype._preActivate = function () {
  32060. var sceneRenderId = this.getScene().getRenderId();
  32061. if (this._preActivateId === sceneRenderId) {
  32062. return this;
  32063. }
  32064. this._preActivateId = sceneRenderId;
  32065. this._visibleInstances = null;
  32066. return this;
  32067. };
  32068. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32069. if (this._visibleInstances) {
  32070. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32071. }
  32072. return this;
  32073. };
  32074. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32075. if (!this._visibleInstances) {
  32076. this._visibleInstances = {};
  32077. this._visibleInstances.defaultRenderId = renderId;
  32078. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32079. }
  32080. if (!this._visibleInstances[renderId]) {
  32081. this._visibleInstances[renderId] = new Array();
  32082. }
  32083. this._visibleInstances[renderId].push(instance);
  32084. return this;
  32085. };
  32086. /**
  32087. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32088. * This means the mesh underlying bounding box and sphere are recomputed.
  32089. * Returns the Mesh.
  32090. */
  32091. Mesh.prototype.refreshBoundingInfo = function () {
  32092. return this._refreshBoundingInfo(false);
  32093. };
  32094. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32095. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32096. return this;
  32097. }
  32098. var data = this._getPositionData(applySkeleton);
  32099. if (data) {
  32100. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32101. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32102. }
  32103. if (this.subMeshes) {
  32104. for (var index = 0; index < this.subMeshes.length; index++) {
  32105. this.subMeshes[index].refreshBoundingInfo();
  32106. }
  32107. }
  32108. this._updateBoundingInfo();
  32109. return this;
  32110. };
  32111. Mesh.prototype._getPositionData = function (applySkeleton) {
  32112. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32113. if (data && applySkeleton && this.skeleton) {
  32114. data = BABYLON.Tools.Slice(data);
  32115. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32116. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32117. if (matricesWeightsData && matricesIndicesData) {
  32118. var needExtras = this.numBoneInfluencers > 4;
  32119. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32120. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32121. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32122. var tempVector = BABYLON.Tmp.Vector3[0];
  32123. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32124. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32125. var matWeightIdx = 0;
  32126. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32127. finalMatrix.reset();
  32128. var inf;
  32129. var weight;
  32130. for (inf = 0; inf < 4; inf++) {
  32131. weight = matricesWeightsData[matWeightIdx + inf];
  32132. if (weight <= 0)
  32133. break;
  32134. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32135. finalMatrix.addToSelf(tempMatrix);
  32136. }
  32137. if (needExtras) {
  32138. for (inf = 0; inf < 4; inf++) {
  32139. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32140. if (weight <= 0)
  32141. break;
  32142. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32143. finalMatrix.addToSelf(tempMatrix);
  32144. }
  32145. }
  32146. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32147. tempVector.toArray(data, index);
  32148. }
  32149. }
  32150. }
  32151. return data;
  32152. };
  32153. Mesh.prototype._createGlobalSubMesh = function (force) {
  32154. var totalVertices = this.getTotalVertices();
  32155. if (!totalVertices || !this.getIndices()) {
  32156. return null;
  32157. }
  32158. // Check if we need to recreate the submeshes
  32159. if (this.subMeshes && this.subMeshes.length > 0) {
  32160. var ib = this.getIndices();
  32161. if (!ib) {
  32162. return null;
  32163. }
  32164. var totalIndices = ib.length;
  32165. var needToRecreate = false;
  32166. if (force) {
  32167. needToRecreate = true;
  32168. }
  32169. else {
  32170. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32171. var submesh = _a[_i];
  32172. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32173. needToRecreate = true;
  32174. break;
  32175. }
  32176. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32177. needToRecreate = true;
  32178. break;
  32179. }
  32180. }
  32181. }
  32182. if (!needToRecreate) {
  32183. return this.subMeshes[0];
  32184. }
  32185. }
  32186. this.releaseSubMeshes();
  32187. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32188. };
  32189. Mesh.prototype.subdivide = function (count) {
  32190. if (count < 1) {
  32191. return;
  32192. }
  32193. var totalIndices = this.getTotalIndices();
  32194. var subdivisionSize = (totalIndices / count) | 0;
  32195. var offset = 0;
  32196. // Ensure that subdivisionSize is a multiple of 3
  32197. while (subdivisionSize % 3 !== 0) {
  32198. subdivisionSize++;
  32199. }
  32200. this.releaseSubMeshes();
  32201. for (var index = 0; index < count; index++) {
  32202. if (offset >= totalIndices) {
  32203. break;
  32204. }
  32205. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32206. offset += subdivisionSize;
  32207. }
  32208. this.synchronizeInstances();
  32209. };
  32210. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32211. if (updatable === void 0) { updatable = false; }
  32212. if (!this._geometry) {
  32213. var vertexData = new BABYLON.VertexData();
  32214. vertexData.set(data, kind);
  32215. var scene = this.getScene();
  32216. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32217. }
  32218. else {
  32219. this._geometry.setVerticesData(kind, data, updatable, stride);
  32220. }
  32221. return this;
  32222. };
  32223. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32224. if (updatable === void 0) { updatable = true; }
  32225. var vb = this.getVertexBuffer(kind);
  32226. if (!vb || vb.isUpdatable() === updatable) {
  32227. return;
  32228. }
  32229. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32230. };
  32231. /**
  32232. * Sets the mesh VertexBuffer.
  32233. * Returns the Mesh.
  32234. */
  32235. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32236. if (!this._geometry) {
  32237. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32238. }
  32239. this._geometry.setVerticesBuffer(buffer);
  32240. return this;
  32241. };
  32242. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32243. if (!this._geometry) {
  32244. return this;
  32245. }
  32246. if (!makeItUnique) {
  32247. this._geometry.updateVerticesData(kind, data, updateExtends);
  32248. }
  32249. else {
  32250. this.makeGeometryUnique();
  32251. this.updateVerticesData(kind, data, updateExtends, false);
  32252. }
  32253. return this;
  32254. };
  32255. /**
  32256. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32257. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32258. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32259. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32260. * Returns the Mesh.
  32261. */
  32262. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32263. if (computeNormals === void 0) { computeNormals = true; }
  32264. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32265. if (!positions) {
  32266. return this;
  32267. }
  32268. positionFunction(positions);
  32269. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32270. if (computeNormals) {
  32271. var indices = this.getIndices();
  32272. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32273. if (!normals) {
  32274. return this;
  32275. }
  32276. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32277. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32278. }
  32279. return this;
  32280. };
  32281. /**
  32282. * Creates a un-shared specific occurence of the geometry for the mesh.
  32283. * Returns the Mesh.
  32284. */
  32285. Mesh.prototype.makeGeometryUnique = function () {
  32286. if (!this._geometry) {
  32287. return this;
  32288. }
  32289. var oldGeometry = this._geometry;
  32290. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32291. oldGeometry.releaseForMesh(this, true);
  32292. geometry.applyToMesh(this);
  32293. return this;
  32294. };
  32295. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32296. if (totalVertices === void 0) { totalVertices = null; }
  32297. if (updatable === void 0) { updatable = false; }
  32298. if (!this._geometry) {
  32299. var vertexData = new BABYLON.VertexData();
  32300. vertexData.indices = indices;
  32301. var scene = this.getScene();
  32302. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32303. }
  32304. else {
  32305. this._geometry.setIndices(indices, totalVertices, updatable);
  32306. }
  32307. return this;
  32308. };
  32309. /**
  32310. * Update the current index buffer
  32311. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32312. * Returns the Mesh.
  32313. */
  32314. Mesh.prototype.updateIndices = function (indices, offset) {
  32315. if (!this._geometry) {
  32316. return this;
  32317. }
  32318. this._geometry.updateIndices(indices, offset);
  32319. return this;
  32320. };
  32321. /**
  32322. * Invert the geometry to move from a right handed system to a left handed one.
  32323. * Returns the Mesh.
  32324. */
  32325. Mesh.prototype.toLeftHanded = function () {
  32326. if (!this._geometry) {
  32327. return this;
  32328. }
  32329. this._geometry.toLeftHanded();
  32330. return this;
  32331. };
  32332. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32333. if (!this._geometry) {
  32334. return this;
  32335. }
  32336. var engine = this.getScene().getEngine();
  32337. // Wireframe
  32338. var indexToBind;
  32339. if (this._unIndexed) {
  32340. indexToBind = null;
  32341. }
  32342. else {
  32343. switch (fillMode) {
  32344. case BABYLON.Material.PointFillMode:
  32345. indexToBind = null;
  32346. break;
  32347. case BABYLON.Material.WireFrameFillMode:
  32348. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32349. break;
  32350. default:
  32351. case BABYLON.Material.TriangleFillMode:
  32352. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32353. break;
  32354. }
  32355. }
  32356. // VBOs
  32357. this._geometry._bind(effect, indexToBind);
  32358. return this;
  32359. };
  32360. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32361. if (alternate === void 0) { alternate = false; }
  32362. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32363. return this;
  32364. }
  32365. this.onBeforeDrawObservable.notifyObservers(this);
  32366. var scene = this.getScene();
  32367. var engine = scene.getEngine();
  32368. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32369. // or triangles as points
  32370. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32371. }
  32372. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32373. // Triangles as wireframe
  32374. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32375. }
  32376. else {
  32377. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32378. }
  32379. if (scene._isAlternateRenderingEnabled && !alternate) {
  32380. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32381. if (!effect || !scene.activeCamera) {
  32382. return this;
  32383. }
  32384. scene._switchToAlternateCameraConfiguration(true);
  32385. this._effectiveMaterial.bindView(effect);
  32386. this._effectiveMaterial.bindViewProjection(effect);
  32387. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32388. this._draw(subMesh, fillMode, instancesCount, true);
  32389. engine.setViewport(scene.activeCamera.viewport);
  32390. scene._switchToAlternateCameraConfiguration(false);
  32391. this._effectiveMaterial.bindView(effect);
  32392. this._effectiveMaterial.bindViewProjection(effect);
  32393. }
  32394. return this;
  32395. };
  32396. /**
  32397. * Registers for this mesh a javascript function called just before the rendering process.
  32398. * This function is passed the current mesh.
  32399. * Return the Mesh.
  32400. */
  32401. Mesh.prototype.registerBeforeRender = function (func) {
  32402. this.onBeforeRenderObservable.add(func);
  32403. return this;
  32404. };
  32405. /**
  32406. * Disposes a previously registered javascript function called before the rendering.
  32407. * This function is passed the current mesh.
  32408. * Returns the Mesh.
  32409. */
  32410. Mesh.prototype.unregisterBeforeRender = function (func) {
  32411. this.onBeforeRenderObservable.removeCallback(func);
  32412. return this;
  32413. };
  32414. /**
  32415. * Registers for this mesh a javascript function called just after the rendering is complete.
  32416. * This function is passed the current mesh.
  32417. * Returns the Mesh.
  32418. */
  32419. Mesh.prototype.registerAfterRender = function (func) {
  32420. this.onAfterRenderObservable.add(func);
  32421. return this;
  32422. };
  32423. /**
  32424. * Disposes a previously registered javascript function called after the rendering.
  32425. * This function is passed the current mesh.
  32426. * Return the Mesh.
  32427. */
  32428. Mesh.prototype.unregisterAfterRender = function (func) {
  32429. this.onAfterRenderObservable.removeCallback(func);
  32430. return this;
  32431. };
  32432. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32433. var scene = this.getScene();
  32434. this._batchCache.mustReturn = false;
  32435. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32436. this._batchCache.visibleInstances[subMeshId] = null;
  32437. if (this._visibleInstances) {
  32438. var currentRenderId = scene.getRenderId();
  32439. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32440. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32441. var selfRenderId = this._renderId;
  32442. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32443. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32444. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32445. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32446. }
  32447. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32448. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32449. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32450. this._batchCache.mustReturn = true;
  32451. return this._batchCache;
  32452. }
  32453. if (currentRenderId !== selfRenderId) {
  32454. this._batchCache.renderSelf[subMeshId] = false;
  32455. }
  32456. }
  32457. this._renderIdForInstances[subMeshId] = currentRenderId;
  32458. }
  32459. return this._batchCache;
  32460. };
  32461. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32462. var visibleInstances = batch.visibleInstances[subMesh._id];
  32463. if (!visibleInstances) {
  32464. return this;
  32465. }
  32466. var matricesCount = visibleInstances.length + 1;
  32467. var bufferSize = matricesCount * 16 * 4;
  32468. var currentInstancesBufferSize = this._instancesBufferSize;
  32469. var instancesBuffer = this._instancesBuffer;
  32470. while (this._instancesBufferSize < bufferSize) {
  32471. this._instancesBufferSize *= 2;
  32472. }
  32473. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32474. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32475. }
  32476. var offset = 0;
  32477. var instancesCount = 0;
  32478. var world = this.getWorldMatrix();
  32479. if (batch.renderSelf[subMesh._id]) {
  32480. world.copyToArray(this._instancesData, offset);
  32481. offset += 16;
  32482. instancesCount++;
  32483. }
  32484. if (visibleInstances) {
  32485. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32486. var instance = visibleInstances[instanceIndex];
  32487. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32488. offset += 16;
  32489. instancesCount++;
  32490. }
  32491. }
  32492. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32493. if (instancesBuffer) {
  32494. instancesBuffer.dispose();
  32495. }
  32496. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32497. this._instancesBuffer = instancesBuffer;
  32498. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32499. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32500. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32501. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32502. }
  32503. else {
  32504. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32505. }
  32506. this._bind(subMesh, effect, fillMode);
  32507. this._draw(subMesh, fillMode, instancesCount);
  32508. engine.unbindInstanceAttributes();
  32509. return this;
  32510. };
  32511. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32512. var scene = this.getScene();
  32513. var engine = scene.getEngine();
  32514. if (hardwareInstancedRendering) {
  32515. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32516. }
  32517. else {
  32518. if (batch.renderSelf[subMesh._id]) {
  32519. // Draw
  32520. if (onBeforeDraw) {
  32521. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32522. }
  32523. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32524. }
  32525. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32526. if (visibleInstancesForSubMesh) {
  32527. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32528. var instance = visibleInstancesForSubMesh[instanceIndex];
  32529. // World
  32530. var world = instance.getWorldMatrix();
  32531. if (onBeforeDraw) {
  32532. onBeforeDraw(true, world, effectiveMaterial);
  32533. }
  32534. // Draw
  32535. this._draw(subMesh, fillMode);
  32536. }
  32537. }
  32538. }
  32539. return this;
  32540. };
  32541. /**
  32542. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32543. * @param subMesh defines the subMesh to render
  32544. * @param enableAlphaMode defines if alpha mode can be changed
  32545. * @returns the current mesh
  32546. */
  32547. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32548. this._checkOcclusionQuery();
  32549. if (this._isOccluded) {
  32550. return this;
  32551. }
  32552. var scene = this.getScene();
  32553. // Managing instances
  32554. var batch = this._getInstancesRenderList(subMesh._id);
  32555. if (batch.mustReturn) {
  32556. return this;
  32557. }
  32558. // Checking geometry state
  32559. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32560. return this;
  32561. }
  32562. this.onBeforeRenderObservable.notifyObservers(this);
  32563. var engine = scene.getEngine();
  32564. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32565. // Material
  32566. var material = subMesh.getMaterial();
  32567. if (!material) {
  32568. return this;
  32569. }
  32570. this._effectiveMaterial = material;
  32571. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32572. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32573. return this;
  32574. }
  32575. }
  32576. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32577. return this;
  32578. }
  32579. // Alpha mode
  32580. if (enableAlphaMode) {
  32581. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32582. }
  32583. // Outline - step 1
  32584. var savedDepthWrite = engine.getDepthWrite();
  32585. if (this.renderOutline) {
  32586. engine.setDepthWrite(false);
  32587. scene.getOutlineRenderer().render(subMesh, batch);
  32588. engine.setDepthWrite(savedDepthWrite);
  32589. }
  32590. var effect;
  32591. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32592. effect = subMesh.effect;
  32593. }
  32594. else {
  32595. effect = this._effectiveMaterial.getEffect();
  32596. }
  32597. if (!effect) {
  32598. return this;
  32599. }
  32600. var sideOrientation = this.overrideMaterialSideOrientation;
  32601. if (sideOrientation == null) {
  32602. sideOrientation = this._effectiveMaterial.sideOrientation;
  32603. if (this._getWorldMatrixDeterminant() < 0) {
  32604. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32605. }
  32606. }
  32607. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32608. if (this._effectiveMaterial.forceDepthWrite) {
  32609. engine.setDepthWrite(true);
  32610. }
  32611. // Bind
  32612. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32613. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32614. this._bind(subMesh, effect, fillMode);
  32615. }
  32616. var world = this.getWorldMatrix();
  32617. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32618. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32619. }
  32620. else {
  32621. this._effectiveMaterial.bind(world, this);
  32622. }
  32623. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32624. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32625. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32626. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32627. }
  32628. // Draw
  32629. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32630. // Unbind
  32631. this._effectiveMaterial.unbind();
  32632. // Outline - step 2
  32633. if (this.renderOutline && savedDepthWrite) {
  32634. engine.setDepthWrite(true);
  32635. engine.setColorWrite(false);
  32636. scene.getOutlineRenderer().render(subMesh, batch);
  32637. engine.setColorWrite(true);
  32638. }
  32639. // Overlay
  32640. if (this.renderOverlay) {
  32641. var currentMode = engine.getAlphaMode();
  32642. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32643. scene.getOutlineRenderer().render(subMesh, batch, true);
  32644. engine.setAlphaMode(currentMode);
  32645. }
  32646. this.onAfterRenderObservable.notifyObservers(this);
  32647. return this;
  32648. };
  32649. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32650. if (isInstance && effectiveMaterial) {
  32651. effectiveMaterial.bindOnlyWorldMatrix(world);
  32652. }
  32653. };
  32654. /**
  32655. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32656. */
  32657. Mesh.prototype.getEmittedParticleSystems = function () {
  32658. var results = new Array();
  32659. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32660. var particleSystem = this.getScene().particleSystems[index];
  32661. if (particleSystem.emitter === this) {
  32662. results.push(particleSystem);
  32663. }
  32664. }
  32665. return results;
  32666. };
  32667. /**
  32668. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32669. */
  32670. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32671. var results = new Array();
  32672. var descendants = this.getDescendants();
  32673. descendants.push(this);
  32674. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32675. var particleSystem = this.getScene().particleSystems[index];
  32676. var emitter = particleSystem.emitter;
  32677. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32678. results.push(particleSystem);
  32679. }
  32680. }
  32681. return results;
  32682. };
  32683. /**
  32684. * Normalize matrix weights so that all vertices have a total weight set to 1
  32685. */
  32686. Mesh.prototype.cleanMatrixWeights = function () {
  32687. var epsilon = 1e-3;
  32688. var noInfluenceBoneIndex = 0.0;
  32689. if (this.skeleton) {
  32690. noInfluenceBoneIndex = this.skeleton.bones.length;
  32691. }
  32692. else {
  32693. return;
  32694. }
  32695. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32696. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32697. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32698. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32699. var influencers = this.numBoneInfluencers;
  32700. var size = matricesWeights.length;
  32701. for (var i = 0; i < size; i += 4) {
  32702. var weight = 0.0;
  32703. var firstZeroWeight = -1;
  32704. for (var j = 0; j < 4; j++) {
  32705. var w = matricesWeights[i + j];
  32706. weight += w;
  32707. if (w < epsilon && firstZeroWeight < 0) {
  32708. firstZeroWeight = j;
  32709. }
  32710. }
  32711. if (matricesWeightsExtra) {
  32712. for (var j = 0; j < 4; j++) {
  32713. var w = matricesWeightsExtra[i + j];
  32714. weight += w;
  32715. if (w < epsilon && firstZeroWeight < 0) {
  32716. firstZeroWeight = j + 4;
  32717. }
  32718. }
  32719. }
  32720. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32721. firstZeroWeight = influencers - 1;
  32722. }
  32723. if (weight > epsilon) {
  32724. var mweight = 1.0 / weight;
  32725. for (var j = 0; j < 4; j++) {
  32726. matricesWeights[i + j] *= mweight;
  32727. }
  32728. if (matricesWeightsExtra) {
  32729. for (var j = 0; j < 4; j++) {
  32730. matricesWeightsExtra[i + j] *= mweight;
  32731. }
  32732. }
  32733. }
  32734. else {
  32735. if (firstZeroWeight >= 4) {
  32736. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32737. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32738. }
  32739. else {
  32740. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32741. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32742. }
  32743. }
  32744. }
  32745. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32746. if (matricesIndicesExtra) {
  32747. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32748. }
  32749. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32750. if (matricesWeightsExtra) {
  32751. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32752. }
  32753. };
  32754. Mesh.prototype._checkDelayState = function () {
  32755. var scene = this.getScene();
  32756. if (this._geometry) {
  32757. this._geometry.load(scene);
  32758. }
  32759. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32760. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32761. this._queueLoad(scene);
  32762. }
  32763. return this;
  32764. };
  32765. Mesh.prototype._queueLoad = function (scene) {
  32766. var _this = this;
  32767. scene._addPendingData(this);
  32768. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32769. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32770. if (data instanceof ArrayBuffer) {
  32771. _this._delayLoadingFunction(data, _this);
  32772. }
  32773. else {
  32774. _this._delayLoadingFunction(JSON.parse(data), _this);
  32775. }
  32776. _this.instances.forEach(function (instance) {
  32777. instance._syncSubMeshes();
  32778. });
  32779. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32780. scene._removePendingData(_this);
  32781. }, function () { }, scene.database, getBinaryData);
  32782. return this;
  32783. };
  32784. /**
  32785. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32786. */
  32787. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32788. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32789. return false;
  32790. }
  32791. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32792. return false;
  32793. }
  32794. this._checkDelayState();
  32795. return true;
  32796. };
  32797. /**
  32798. * Sets the mesh material by the material or multiMaterial `id` property.
  32799. * The material `id` is a string identifying the material or the multiMaterial.
  32800. * This method returns the Mesh.
  32801. */
  32802. Mesh.prototype.setMaterialByID = function (id) {
  32803. var materials = this.getScene().materials;
  32804. var index;
  32805. for (index = materials.length - 1; index > -1; index--) {
  32806. if (materials[index].id === id) {
  32807. this.material = materials[index];
  32808. return this;
  32809. }
  32810. }
  32811. // Multi
  32812. var multiMaterials = this.getScene().multiMaterials;
  32813. for (index = multiMaterials.length - 1; index > -1; index--) {
  32814. if (multiMaterials[index].id === id) {
  32815. this.material = multiMaterials[index];
  32816. return this;
  32817. }
  32818. }
  32819. return this;
  32820. };
  32821. /**
  32822. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32823. */
  32824. Mesh.prototype.getAnimatables = function () {
  32825. var results = new Array();
  32826. if (this.material) {
  32827. results.push(this.material);
  32828. }
  32829. if (this.skeleton) {
  32830. results.push(this.skeleton);
  32831. }
  32832. return results;
  32833. };
  32834. /**
  32835. * Modifies the mesh geometry according to the passed transformation matrix.
  32836. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32837. * The mesh normals are modified accordingly the same transformation.
  32838. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32839. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32840. * Returns the Mesh.
  32841. */
  32842. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32843. // Position
  32844. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32845. return this;
  32846. }
  32847. var submeshes = this.subMeshes.splice(0);
  32848. this._resetPointsArrayCache();
  32849. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32850. var temp = new Array();
  32851. var index;
  32852. for (index = 0; index < data.length; index += 3) {
  32853. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32854. }
  32855. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32856. // Normals
  32857. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32858. return this;
  32859. }
  32860. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32861. temp = [];
  32862. for (index = 0; index < data.length; index += 3) {
  32863. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32864. }
  32865. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32866. // flip faces?
  32867. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32868. this.flipFaces();
  32869. }
  32870. // Restore submeshes
  32871. this.releaseSubMeshes();
  32872. this.subMeshes = submeshes;
  32873. return this;
  32874. };
  32875. /**
  32876. * Modifies the mesh geometry according to its own current World Matrix.
  32877. * The mesh World Matrix is then reset.
  32878. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32879. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32880. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32881. * Returns the Mesh.
  32882. */
  32883. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32884. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32885. this.scaling.copyFromFloats(1, 1, 1);
  32886. this.position.copyFromFloats(0, 0, 0);
  32887. this.rotation.copyFromFloats(0, 0, 0);
  32888. //only if quaternion is already set
  32889. if (this.rotationQuaternion) {
  32890. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32891. }
  32892. this._worldMatrix = BABYLON.Matrix.Identity();
  32893. return this;
  32894. };
  32895. Object.defineProperty(Mesh.prototype, "_positions", {
  32896. // Cache
  32897. get: function () {
  32898. if (this._geometry) {
  32899. return this._geometry._positions;
  32900. }
  32901. return null;
  32902. },
  32903. enumerable: true,
  32904. configurable: true
  32905. });
  32906. Mesh.prototype._resetPointsArrayCache = function () {
  32907. if (this._geometry) {
  32908. this._geometry._resetPointsArrayCache();
  32909. }
  32910. return this;
  32911. };
  32912. Mesh.prototype._generatePointsArray = function () {
  32913. if (this._geometry) {
  32914. return this._geometry._generatePointsArray();
  32915. }
  32916. return false;
  32917. };
  32918. /**
  32919. * Returns a new Mesh object generated from the current mesh properties.
  32920. * This method must not get confused with createInstance().
  32921. * The parameter `name` is a string, the name given to the new mesh.
  32922. * The optional parameter `newParent` can be any Node object (default `null`).
  32923. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32924. * 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.
  32925. */
  32926. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32927. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32928. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32929. };
  32930. /**
  32931. * Releases resources associated with this mesh.
  32932. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32933. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32934. */
  32935. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32936. var _this = this;
  32937. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32938. this.morphTargetManager = null;
  32939. if (this._geometry) {
  32940. this._geometry.releaseForMesh(this, true);
  32941. }
  32942. // Sources
  32943. var meshes = this.getScene().meshes;
  32944. meshes.forEach(function (abstractMesh) {
  32945. var mesh = abstractMesh;
  32946. if (mesh._source && mesh._source === _this) {
  32947. mesh._source = null;
  32948. }
  32949. });
  32950. this._source = null;
  32951. // Instances
  32952. if (this._instancesBuffer) {
  32953. this._instancesBuffer.dispose();
  32954. this._instancesBuffer = null;
  32955. }
  32956. while (this.instances.length) {
  32957. this.instances[0].dispose();
  32958. }
  32959. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32960. };
  32961. /**
  32962. * Modifies the mesh geometry according to a displacement map.
  32963. * 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.
  32964. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32965. * This method returns nothing.
  32966. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32967. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32968. * 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.
  32969. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32970. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32971. *
  32972. * Returns the Mesh.
  32973. */
  32974. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32975. var _this = this;
  32976. var scene = this.getScene();
  32977. var onload = function (img) {
  32978. // Getting height map data
  32979. var canvas = document.createElement("canvas");
  32980. var context = canvas.getContext("2d");
  32981. var heightMapWidth = img.width;
  32982. var heightMapHeight = img.height;
  32983. canvas.width = heightMapWidth;
  32984. canvas.height = heightMapHeight;
  32985. context.drawImage(img, 0, 0);
  32986. // Create VertexData from map data
  32987. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32988. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32989. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32990. //execute success callback, if set
  32991. if (onSuccess) {
  32992. onSuccess(_this);
  32993. }
  32994. };
  32995. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32996. return this;
  32997. };
  32998. /**
  32999. * Modifies the mesh geometry according to a displacementMap buffer.
  33000. * 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.
  33001. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33002. * This method returns nothing.
  33003. * 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.
  33004. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33005. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33006. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33007. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33008. *
  33009. * Returns the Mesh.
  33010. */
  33011. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33012. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33013. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33014. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33015. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33016. return this;
  33017. }
  33018. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33019. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33020. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33021. var position = BABYLON.Vector3.Zero();
  33022. var normal = BABYLON.Vector3.Zero();
  33023. var uv = BABYLON.Vector2.Zero();
  33024. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33025. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33026. for (var index = 0; index < positions.length; index += 3) {
  33027. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33028. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33029. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33030. // Compute height
  33031. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33032. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33033. var pos = (u + v * heightMapWidth) * 4;
  33034. var r = buffer[pos] / 255.0;
  33035. var g = buffer[pos + 1] / 255.0;
  33036. var b = buffer[pos + 2] / 255.0;
  33037. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33038. normal.normalize();
  33039. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33040. position = position.add(normal);
  33041. position.toArray(positions, index);
  33042. }
  33043. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33044. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33045. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33046. return this;
  33047. };
  33048. /**
  33049. * Modify the mesh to get a flat shading rendering.
  33050. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33051. * This method returns the Mesh.
  33052. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33053. */
  33054. Mesh.prototype.convertToFlatShadedMesh = function () {
  33055. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33056. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33057. var kinds = this.getVerticesDataKinds();
  33058. var vbs = {};
  33059. var data = {};
  33060. var newdata = {};
  33061. var updatableNormals = false;
  33062. var kindIndex;
  33063. var kind;
  33064. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33065. kind = kinds[kindIndex];
  33066. var vertexBuffer = this.getVertexBuffer(kind);
  33067. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33068. updatableNormals = vertexBuffer.isUpdatable();
  33069. kinds.splice(kindIndex, 1);
  33070. kindIndex--;
  33071. continue;
  33072. }
  33073. vbs[kind] = vertexBuffer;
  33074. data[kind] = vbs[kind].getData();
  33075. newdata[kind] = [];
  33076. }
  33077. // Save previous submeshes
  33078. var previousSubmeshes = this.subMeshes.slice(0);
  33079. var indices = this.getIndices();
  33080. var totalIndices = this.getTotalIndices();
  33081. // Generating unique vertices per face
  33082. var index;
  33083. for (index = 0; index < totalIndices; index++) {
  33084. var vertexIndex = indices[index];
  33085. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33086. kind = kinds[kindIndex];
  33087. var stride = vbs[kind].getStrideSize();
  33088. for (var offset = 0; offset < stride; offset++) {
  33089. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33090. }
  33091. }
  33092. }
  33093. // Updating faces & normal
  33094. var normals = [];
  33095. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33096. for (index = 0; index < totalIndices; index += 3) {
  33097. indices[index] = index;
  33098. indices[index + 1] = index + 1;
  33099. indices[index + 2] = index + 2;
  33100. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33101. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33102. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33103. var p1p2 = p1.subtract(p2);
  33104. var p3p2 = p3.subtract(p2);
  33105. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33106. // Store same normals for every vertex
  33107. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33108. normals.push(normal.x);
  33109. normals.push(normal.y);
  33110. normals.push(normal.z);
  33111. }
  33112. }
  33113. this.setIndices(indices);
  33114. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33115. // Updating vertex buffers
  33116. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33117. kind = kinds[kindIndex];
  33118. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33119. }
  33120. // Updating submeshes
  33121. this.releaseSubMeshes();
  33122. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33123. var previousOne = previousSubmeshes[submeshIndex];
  33124. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33125. }
  33126. this.synchronizeInstances();
  33127. return this;
  33128. };
  33129. /**
  33130. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33131. * In other words, more vertices, no more indices and a single bigger VBO.
  33132. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33133. * Returns the Mesh.
  33134. */
  33135. Mesh.prototype.convertToUnIndexedMesh = function () {
  33136. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33137. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33138. var kinds = this.getVerticesDataKinds();
  33139. var vbs = {};
  33140. var data = {};
  33141. var newdata = {};
  33142. var kindIndex;
  33143. var kind;
  33144. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33145. kind = kinds[kindIndex];
  33146. var vertexBuffer = this.getVertexBuffer(kind);
  33147. vbs[kind] = vertexBuffer;
  33148. data[kind] = vbs[kind].getData();
  33149. newdata[kind] = [];
  33150. }
  33151. // Save previous submeshes
  33152. var previousSubmeshes = this.subMeshes.slice(0);
  33153. var indices = this.getIndices();
  33154. var totalIndices = this.getTotalIndices();
  33155. // Generating unique vertices per face
  33156. var index;
  33157. for (index = 0; index < totalIndices; index++) {
  33158. var vertexIndex = indices[index];
  33159. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33160. kind = kinds[kindIndex];
  33161. var stride = vbs[kind].getStrideSize();
  33162. for (var offset = 0; offset < stride; offset++) {
  33163. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33164. }
  33165. }
  33166. }
  33167. // Updating indices
  33168. for (index = 0; index < totalIndices; index += 3) {
  33169. indices[index] = index;
  33170. indices[index + 1] = index + 1;
  33171. indices[index + 2] = index + 2;
  33172. }
  33173. this.setIndices(indices);
  33174. // Updating vertex buffers
  33175. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33176. kind = kinds[kindIndex];
  33177. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33178. }
  33179. // Updating submeshes
  33180. this.releaseSubMeshes();
  33181. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33182. var previousOne = previousSubmeshes[submeshIndex];
  33183. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33184. }
  33185. this._unIndexed = true;
  33186. this.synchronizeInstances();
  33187. return this;
  33188. };
  33189. /**
  33190. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33191. * This method returns the Mesh.
  33192. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33193. */
  33194. Mesh.prototype.flipFaces = function (flipNormals) {
  33195. if (flipNormals === void 0) { flipNormals = false; }
  33196. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33197. var i;
  33198. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33199. for (i = 0; i < vertex_data.normals.length; i++) {
  33200. vertex_data.normals[i] *= -1;
  33201. }
  33202. }
  33203. if (vertex_data.indices) {
  33204. var temp;
  33205. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33206. // reassign indices
  33207. temp = vertex_data.indices[i + 1];
  33208. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33209. vertex_data.indices[i + 2] = temp;
  33210. }
  33211. }
  33212. vertex_data.applyToMesh(this);
  33213. return this;
  33214. };
  33215. // Instances
  33216. /**
  33217. * Creates a new InstancedMesh object from the mesh model.
  33218. * An instance shares the same properties and the same material than its model.
  33219. * Only these properties of each instance can then be set individually :
  33220. * - position
  33221. * - rotation
  33222. * - rotationQuaternion
  33223. * - setPivotMatrix
  33224. * - scaling
  33225. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33226. * Warning : this method is not supported for Line mesh and LineSystem
  33227. */
  33228. Mesh.prototype.createInstance = function (name) {
  33229. return new BABYLON.InstancedMesh(name, this);
  33230. };
  33231. /**
  33232. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33233. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33234. * This method returns the Mesh.
  33235. */
  33236. Mesh.prototype.synchronizeInstances = function () {
  33237. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33238. var instance = this.instances[instanceIndex];
  33239. instance._syncSubMeshes();
  33240. }
  33241. return this;
  33242. };
  33243. /**
  33244. * Simplify the mesh according to the given array of settings.
  33245. * Function will return immediately and will simplify async. It returns the Mesh.
  33246. * @param settings a collection of simplification settings.
  33247. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33248. * @param type the type of simplification to run.
  33249. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33250. */
  33251. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33252. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33253. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33254. this.getScene().simplificationQueue.addTask({
  33255. settings: settings,
  33256. parallelProcessing: parallelProcessing,
  33257. mesh: this,
  33258. simplificationType: simplificationType,
  33259. successCallback: successCallback
  33260. });
  33261. return this;
  33262. };
  33263. /**
  33264. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33265. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33266. * This should be used together with the simplification to avoid disappearing triangles.
  33267. * Returns the Mesh.
  33268. * @param successCallback an optional success callback to be called after the optimization finished.
  33269. */
  33270. Mesh.prototype.optimizeIndices = function (successCallback) {
  33271. var _this = this;
  33272. var indices = this.getIndices();
  33273. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33274. if (!positions || !indices) {
  33275. return this;
  33276. }
  33277. var vectorPositions = new Array();
  33278. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33279. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33280. }
  33281. var dupes = new Array();
  33282. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33283. var realPos = vectorPositions.length - 1 - iteration;
  33284. var testedPosition = vectorPositions[realPos];
  33285. for (var j = 0; j < realPos; ++j) {
  33286. var againstPosition = vectorPositions[j];
  33287. if (testedPosition.equals(againstPosition)) {
  33288. dupes[realPos] = j;
  33289. break;
  33290. }
  33291. }
  33292. }, function () {
  33293. for (var i = 0; i < indices.length; ++i) {
  33294. indices[i] = dupes[indices[i]] || indices[i];
  33295. }
  33296. //indices are now reordered
  33297. var originalSubMeshes = _this.subMeshes.slice(0);
  33298. _this.setIndices(indices);
  33299. _this.subMeshes = originalSubMeshes;
  33300. if (successCallback) {
  33301. successCallback(_this);
  33302. }
  33303. });
  33304. return this;
  33305. };
  33306. Mesh.prototype.serialize = function (serializationObject) {
  33307. serializationObject.name = this.name;
  33308. serializationObject.id = this.id;
  33309. serializationObject.type = this.getClassName();
  33310. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33311. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33312. }
  33313. serializationObject.position = this.position.asArray();
  33314. if (this.rotationQuaternion) {
  33315. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33316. }
  33317. else if (this.rotation) {
  33318. serializationObject.rotation = this.rotation.asArray();
  33319. }
  33320. serializationObject.scaling = this.scaling.asArray();
  33321. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33322. serializationObject.isEnabled = this.isEnabled(false);
  33323. serializationObject.isVisible = this.isVisible;
  33324. serializationObject.infiniteDistance = this.infiniteDistance;
  33325. serializationObject.pickable = this.isPickable;
  33326. serializationObject.receiveShadows = this.receiveShadows;
  33327. serializationObject.billboardMode = this.billboardMode;
  33328. serializationObject.visibility = this.visibility;
  33329. serializationObject.checkCollisions = this.checkCollisions;
  33330. serializationObject.isBlocker = this.isBlocker;
  33331. // Parent
  33332. if (this.parent) {
  33333. serializationObject.parentId = this.parent.id;
  33334. }
  33335. // Geometry
  33336. serializationObject.isUnIndexed = this.isUnIndexed;
  33337. var geometry = this._geometry;
  33338. if (geometry) {
  33339. var geometryId = geometry.id;
  33340. serializationObject.geometryId = geometryId;
  33341. // SubMeshes
  33342. serializationObject.subMeshes = [];
  33343. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33344. var subMesh = this.subMeshes[subIndex];
  33345. serializationObject.subMeshes.push({
  33346. materialIndex: subMesh.materialIndex,
  33347. verticesStart: subMesh.verticesStart,
  33348. verticesCount: subMesh.verticesCount,
  33349. indexStart: subMesh.indexStart,
  33350. indexCount: subMesh.indexCount
  33351. });
  33352. }
  33353. }
  33354. // Material
  33355. if (this.material) {
  33356. serializationObject.materialId = this.material.id;
  33357. }
  33358. else {
  33359. this.material = null;
  33360. }
  33361. // Morph targets
  33362. if (this.morphTargetManager) {
  33363. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33364. }
  33365. // Skeleton
  33366. if (this.skeleton) {
  33367. serializationObject.skeletonId = this.skeleton.id;
  33368. }
  33369. // Physics
  33370. //TODO implement correct serialization for physics impostors.
  33371. var impostor = this.getPhysicsImpostor();
  33372. if (impostor) {
  33373. serializationObject.physicsMass = impostor.getParam("mass");
  33374. serializationObject.physicsFriction = impostor.getParam("friction");
  33375. serializationObject.physicsRestitution = impostor.getParam("mass");
  33376. serializationObject.physicsImpostor = impostor.type;
  33377. }
  33378. // Metadata
  33379. if (this.metadata) {
  33380. serializationObject.metadata = this.metadata;
  33381. }
  33382. // Instances
  33383. serializationObject.instances = [];
  33384. for (var index = 0; index < this.instances.length; index++) {
  33385. var instance = this.instances[index];
  33386. var serializationInstance = {
  33387. name: instance.name,
  33388. id: instance.id,
  33389. position: instance.position.asArray(),
  33390. scaling: instance.scaling.asArray()
  33391. };
  33392. if (instance.rotationQuaternion) {
  33393. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33394. }
  33395. else if (instance.rotation) {
  33396. serializationInstance.rotation = instance.rotation.asArray();
  33397. }
  33398. serializationObject.instances.push(serializationInstance);
  33399. // Animations
  33400. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33401. serializationInstance.ranges = instance.serializeAnimationRanges();
  33402. }
  33403. //
  33404. // Animations
  33405. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33406. serializationObject.ranges = this.serializeAnimationRanges();
  33407. // Layer mask
  33408. serializationObject.layerMask = this.layerMask;
  33409. // Alpha
  33410. serializationObject.alphaIndex = this.alphaIndex;
  33411. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33412. // Overlay
  33413. serializationObject.overlayAlpha = this.overlayAlpha;
  33414. serializationObject.overlayColor = this.overlayColor.asArray();
  33415. serializationObject.renderOverlay = this.renderOverlay;
  33416. // Fog
  33417. serializationObject.applyFog = this.applyFog;
  33418. // Action Manager
  33419. if (this.actionManager) {
  33420. serializationObject.actions = this.actionManager.serialize(this.name);
  33421. }
  33422. };
  33423. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33424. if (!this.geometry) {
  33425. return;
  33426. }
  33427. this._markSubMeshesAsAttributesDirty();
  33428. var morphTargetManager = this._morphTargetManager;
  33429. if (morphTargetManager && morphTargetManager.vertexCount) {
  33430. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33431. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33432. this.morphTargetManager = null;
  33433. return;
  33434. }
  33435. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33436. var morphTarget = morphTargetManager.getActiveTarget(index);
  33437. var positions = morphTarget.getPositions();
  33438. if (!positions) {
  33439. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33440. return;
  33441. }
  33442. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33443. var normals = morphTarget.getNormals();
  33444. if (normals) {
  33445. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33446. }
  33447. var tangents = morphTarget.getTangents();
  33448. if (tangents) {
  33449. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33450. }
  33451. }
  33452. }
  33453. else {
  33454. var index = 0;
  33455. // Positions
  33456. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33457. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33458. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33459. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33460. }
  33461. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33462. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33463. }
  33464. index++;
  33465. }
  33466. }
  33467. };
  33468. // Statics
  33469. /**
  33470. * Returns a new Mesh object parsed from the source provided.
  33471. * The parameter `parsedMesh` is the source.
  33472. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33473. */
  33474. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33475. var mesh;
  33476. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33477. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33478. }
  33479. else {
  33480. mesh = new Mesh(parsedMesh.name, scene);
  33481. }
  33482. mesh.id = parsedMesh.id;
  33483. if (BABYLON.Tags) {
  33484. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33485. }
  33486. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33487. if (parsedMesh.metadata !== undefined) {
  33488. mesh.metadata = parsedMesh.metadata;
  33489. }
  33490. if (parsedMesh.rotationQuaternion) {
  33491. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33492. }
  33493. else if (parsedMesh.rotation) {
  33494. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33495. }
  33496. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33497. if (parsedMesh.localMatrix) {
  33498. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33499. }
  33500. else if (parsedMesh.pivotMatrix) {
  33501. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33502. }
  33503. mesh.setEnabled(parsedMesh.isEnabled);
  33504. mesh.isVisible = parsedMesh.isVisible;
  33505. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33506. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33507. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33508. if (parsedMesh.applyFog !== undefined) {
  33509. mesh.applyFog = parsedMesh.applyFog;
  33510. }
  33511. if (parsedMesh.pickable !== undefined) {
  33512. mesh.isPickable = parsedMesh.pickable;
  33513. }
  33514. if (parsedMesh.alphaIndex !== undefined) {
  33515. mesh.alphaIndex = parsedMesh.alphaIndex;
  33516. }
  33517. mesh.receiveShadows = parsedMesh.receiveShadows;
  33518. mesh.billboardMode = parsedMesh.billboardMode;
  33519. if (parsedMesh.visibility !== undefined) {
  33520. mesh.visibility = parsedMesh.visibility;
  33521. }
  33522. mesh.checkCollisions = parsedMesh.checkCollisions;
  33523. if (parsedMesh.isBlocker !== undefined) {
  33524. mesh.isBlocker = parsedMesh.isBlocker;
  33525. }
  33526. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33527. // freezeWorldMatrix
  33528. if (parsedMesh.freezeWorldMatrix) {
  33529. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33530. }
  33531. // Parent
  33532. if (parsedMesh.parentId) {
  33533. mesh._waitingParentId = parsedMesh.parentId;
  33534. }
  33535. // Actions
  33536. if (parsedMesh.actions !== undefined) {
  33537. mesh._waitingActions = parsedMesh.actions;
  33538. }
  33539. // Overlay
  33540. if (parsedMesh.overlayAlpha !== undefined) {
  33541. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33542. }
  33543. if (parsedMesh.overlayColor !== undefined) {
  33544. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33545. }
  33546. if (parsedMesh.renderOverlay !== undefined) {
  33547. mesh.renderOverlay = parsedMesh.renderOverlay;
  33548. }
  33549. // Geometry
  33550. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33551. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33552. if (parsedMesh.delayLoadingFile) {
  33553. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33554. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33555. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33556. if (parsedMesh._binaryInfo) {
  33557. mesh._binaryInfo = parsedMesh._binaryInfo;
  33558. }
  33559. mesh._delayInfo = [];
  33560. if (parsedMesh.hasUVs) {
  33561. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33562. }
  33563. if (parsedMesh.hasUVs2) {
  33564. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33565. }
  33566. if (parsedMesh.hasUVs3) {
  33567. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33568. }
  33569. if (parsedMesh.hasUVs4) {
  33570. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33571. }
  33572. if (parsedMesh.hasUVs5) {
  33573. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33574. }
  33575. if (parsedMesh.hasUVs6) {
  33576. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33577. }
  33578. if (parsedMesh.hasColors) {
  33579. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33580. }
  33581. if (parsedMesh.hasMatricesIndices) {
  33582. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33583. }
  33584. if (parsedMesh.hasMatricesWeights) {
  33585. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33586. }
  33587. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33588. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33589. mesh._checkDelayState();
  33590. }
  33591. }
  33592. else {
  33593. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33594. }
  33595. // Material
  33596. if (parsedMesh.materialId) {
  33597. mesh.setMaterialByID(parsedMesh.materialId);
  33598. }
  33599. else {
  33600. mesh.material = null;
  33601. }
  33602. // Morph targets
  33603. if (parsedMesh.morphTargetManagerId > -1) {
  33604. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33605. }
  33606. // Skeleton
  33607. if (parsedMesh.skeletonId > -1) {
  33608. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33609. if (parsedMesh.numBoneInfluencers) {
  33610. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33611. }
  33612. }
  33613. // Animations
  33614. if (parsedMesh.animations) {
  33615. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33616. var parsedAnimation = parsedMesh.animations[animationIndex];
  33617. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33618. }
  33619. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33620. }
  33621. if (parsedMesh.autoAnimate) {
  33622. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33623. }
  33624. // Layer Mask
  33625. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33626. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33627. }
  33628. else {
  33629. mesh.layerMask = 0x0FFFFFFF;
  33630. }
  33631. // Physics
  33632. if (parsedMesh.physicsImpostor) {
  33633. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33634. mass: parsedMesh.physicsMass,
  33635. friction: parsedMesh.physicsFriction,
  33636. restitution: parsedMesh.physicsRestitution
  33637. }, scene);
  33638. }
  33639. // Instances
  33640. if (parsedMesh.instances) {
  33641. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33642. var parsedInstance = parsedMesh.instances[index];
  33643. var instance = mesh.createInstance(parsedInstance.name);
  33644. if (parsedInstance.id) {
  33645. instance.id = parsedInstance.id;
  33646. }
  33647. if (BABYLON.Tags) {
  33648. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33649. }
  33650. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33651. if (parsedInstance.parentId) {
  33652. instance._waitingParentId = parsedInstance.parentId;
  33653. }
  33654. if (parsedInstance.rotationQuaternion) {
  33655. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33656. }
  33657. else if (parsedInstance.rotation) {
  33658. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33659. }
  33660. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33661. instance.checkCollisions = mesh.checkCollisions;
  33662. if (parsedMesh.animations) {
  33663. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33664. parsedAnimation = parsedMesh.animations[animationIndex];
  33665. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33666. }
  33667. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33668. if (parsedMesh.autoAnimate) {
  33669. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33670. }
  33671. }
  33672. }
  33673. }
  33674. return mesh;
  33675. };
  33676. /**
  33677. * Creates a ribbon mesh.
  33678. * Please consider using the same method from the MeshBuilder class instead.
  33679. * 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.
  33680. *
  33681. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33682. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33683. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33684. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33685. * 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.
  33686. * 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.
  33687. * 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
  33688. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33689. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33690. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33691. */
  33692. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33693. if (closeArray === void 0) { closeArray = false; }
  33694. if (updatable === void 0) { updatable = false; }
  33695. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33696. pathArray: pathArray,
  33697. closeArray: closeArray,
  33698. closePath: closePath,
  33699. offset: offset,
  33700. updatable: updatable,
  33701. sideOrientation: sideOrientation,
  33702. instance: instance
  33703. }, scene);
  33704. };
  33705. /**
  33706. * Creates a plane polygonal mesh. By default, this is a disc.
  33707. * Please consider using the same method from the MeshBuilder class instead.
  33708. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33709. * 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.
  33710. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33711. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33713. */
  33714. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33715. if (scene === void 0) { scene = null; }
  33716. var options = {
  33717. radius: radius,
  33718. tessellation: tessellation,
  33719. sideOrientation: sideOrientation,
  33720. updatable: updatable
  33721. };
  33722. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33723. };
  33724. /**
  33725. * Creates a box mesh.
  33726. * Please consider using the same method from the MeshBuilder class instead.
  33727. * The parameter `size` sets the size (float) of each box side (default 1).
  33728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33729. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33731. */
  33732. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33733. if (scene === void 0) { scene = null; }
  33734. var options = {
  33735. size: size,
  33736. sideOrientation: sideOrientation,
  33737. updatable: updatable
  33738. };
  33739. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33740. };
  33741. /**
  33742. * Creates a sphere mesh.
  33743. * Please consider using the same method from the MeshBuilder class instead.
  33744. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33745. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33746. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33747. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33748. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33749. */
  33750. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33751. var options = {
  33752. segments: segments,
  33753. diameterX: diameter,
  33754. diameterY: diameter,
  33755. diameterZ: diameter,
  33756. sideOrientation: sideOrientation,
  33757. updatable: updatable
  33758. };
  33759. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33760. };
  33761. /**
  33762. * Creates a cylinder or a cone mesh.
  33763. * Please consider using the same method from the MeshBuilder class instead.
  33764. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33765. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33766. * 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.
  33767. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33768. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33769. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33770. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33772. */
  33773. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33774. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33775. if (scene !== undefined) {
  33776. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33777. updatable = scene;
  33778. }
  33779. scene = subdivisions;
  33780. subdivisions = 1;
  33781. }
  33782. var options = {
  33783. height: height,
  33784. diameterTop: diameterTop,
  33785. diameterBottom: diameterBottom,
  33786. tessellation: tessellation,
  33787. subdivisions: subdivisions,
  33788. sideOrientation: sideOrientation,
  33789. updatable: updatable
  33790. };
  33791. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33792. };
  33793. // Torus (Code from SharpDX.org)
  33794. /**
  33795. * Creates a torus mesh.
  33796. * Please consider using the same method from the MeshBuilder class instead.
  33797. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33798. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33799. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33801. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33803. */
  33804. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33805. var options = {
  33806. diameter: diameter,
  33807. thickness: thickness,
  33808. tessellation: tessellation,
  33809. sideOrientation: sideOrientation,
  33810. updatable: updatable
  33811. };
  33812. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33813. };
  33814. /**
  33815. * Creates a torus knot mesh.
  33816. * Please consider using the same method from the MeshBuilder class instead.
  33817. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33818. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33819. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33820. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33822. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33824. */
  33825. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33826. var options = {
  33827. radius: radius,
  33828. tube: tube,
  33829. radialSegments: radialSegments,
  33830. tubularSegments: tubularSegments,
  33831. p: p,
  33832. q: q,
  33833. sideOrientation: sideOrientation,
  33834. updatable: updatable
  33835. };
  33836. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33837. };
  33838. /**
  33839. * Creates a line mesh.
  33840. * Please consider using the same method from the MeshBuilder class instead.
  33841. * 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.
  33842. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33843. * The parameter `points` is an array successive Vector3.
  33844. * 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
  33845. * When updating an instance, remember that only point positions can change, not the number of points.
  33846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33847. */
  33848. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33849. if (scene === void 0) { scene = null; }
  33850. if (updatable === void 0) { updatable = false; }
  33851. if (instance === void 0) { instance = null; }
  33852. var options = {
  33853. points: points,
  33854. updatable: updatable,
  33855. instance: instance
  33856. };
  33857. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33858. };
  33859. /**
  33860. * Creates a dashed line mesh.
  33861. * Please consider using the same method from the MeshBuilder class instead.
  33862. * 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.
  33863. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33864. * The parameter `points` is an array successive Vector3.
  33865. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33866. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33867. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33868. * 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
  33869. * When updating an instance, remember that only point positions can change, not the number of points.
  33870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33871. */
  33872. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33873. if (scene === void 0) { scene = null; }
  33874. var options = {
  33875. points: points,
  33876. dashSize: dashSize,
  33877. gapSize: gapSize,
  33878. dashNb: dashNb,
  33879. updatable: updatable,
  33880. instance: instance
  33881. };
  33882. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33883. };
  33884. /**
  33885. * Creates a polygon mesh.
  33886. * Please consider using the same method from the MeshBuilder class instead.
  33887. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33888. * 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.
  33889. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33891. * Remember you can only change the shape positions, not their number when updating a polygon.
  33892. */
  33893. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33894. var options = {
  33895. shape: shape,
  33896. holes: holes,
  33897. updatable: updatable,
  33898. sideOrientation: sideOrientation
  33899. };
  33900. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33901. };
  33902. /**
  33903. * Creates an extruded polygon mesh, with depth in the Y direction.
  33904. * Please consider using the same method from the MeshBuilder class instead.
  33905. */
  33906. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33907. var options = {
  33908. shape: shape,
  33909. holes: holes,
  33910. depth: depth,
  33911. updatable: updatable,
  33912. sideOrientation: sideOrientation
  33913. };
  33914. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33915. };
  33916. /**
  33917. * Creates an extruded shape mesh.
  33918. * 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.
  33919. * Please consider using the same method from the MeshBuilder class instead.
  33920. *
  33921. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33922. * 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
  33923. * extruded along the Z axis.
  33924. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33925. * 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.
  33926. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33927. * 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
  33928. * 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
  33929. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33931. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33933. */
  33934. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33935. if (scene === void 0) { scene = null; }
  33936. var options = {
  33937. shape: shape,
  33938. path: path,
  33939. scale: scale,
  33940. rotation: rotation,
  33941. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33942. sideOrientation: sideOrientation,
  33943. instance: instance,
  33944. updatable: updatable
  33945. };
  33946. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33947. };
  33948. /**
  33949. * Creates an custom extruded shape mesh.
  33950. * 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.
  33951. * Please consider using the same method from the MeshBuilder class instead.
  33952. *
  33953. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33954. * 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
  33955. * extruded along the Z axis.
  33956. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33957. * 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
  33958. * and the distance of this point from the begining of the path :
  33959. * ```javascript
  33960. * var rotationFunction = function(i, distance) {
  33961. * // do things
  33962. * return rotationValue; }
  33963. * ```
  33964. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33965. * 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
  33966. * and the distance of this point from the begining of the path :
  33967. * ```javascript
  33968. * var scaleFunction = function(i, distance) {
  33969. * // do things
  33970. * return scaleValue;}
  33971. * ```
  33972. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33973. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33974. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33975. * 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
  33976. * 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
  33977. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33979. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33981. */
  33982. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33983. var options = {
  33984. shape: shape,
  33985. path: path,
  33986. scaleFunction: scaleFunction,
  33987. rotationFunction: rotationFunction,
  33988. ribbonCloseArray: ribbonCloseArray,
  33989. ribbonClosePath: ribbonClosePath,
  33990. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33991. sideOrientation: sideOrientation,
  33992. instance: instance,
  33993. updatable: updatable
  33994. };
  33995. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33996. };
  33997. /**
  33998. * Creates lathe mesh.
  33999. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34000. * Please consider using the same method from the MeshBuilder class instead.
  34001. * 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
  34002. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34003. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34004. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34005. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34006. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34008. */
  34009. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34010. var options = {
  34011. shape: shape,
  34012. radius: radius,
  34013. tessellation: tessellation,
  34014. sideOrientation: sideOrientation,
  34015. updatable: updatable
  34016. };
  34017. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34018. };
  34019. /**
  34020. * Creates a plane mesh.
  34021. * Please consider using the same method from the MeshBuilder class instead.
  34022. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34024. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34025. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34026. */
  34027. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34028. var options = {
  34029. size: size,
  34030. width: size,
  34031. height: size,
  34032. sideOrientation: sideOrientation,
  34033. updatable: updatable
  34034. };
  34035. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34036. };
  34037. /**
  34038. * Creates a ground mesh.
  34039. * Please consider using the same method from the MeshBuilder class instead.
  34040. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34041. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34043. */
  34044. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34045. var options = {
  34046. width: width,
  34047. height: height,
  34048. subdivisions: subdivisions,
  34049. updatable: updatable
  34050. };
  34051. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34052. };
  34053. /**
  34054. * Creates a tiled ground mesh.
  34055. * Please consider using the same method from the MeshBuilder class instead.
  34056. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34057. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34058. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34059. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34060. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34061. * numbers of subdivisions on the ground width and height of each tile.
  34062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34063. */
  34064. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34065. var options = {
  34066. xmin: xmin,
  34067. zmin: zmin,
  34068. xmax: xmax,
  34069. zmax: zmax,
  34070. subdivisions: subdivisions,
  34071. precision: precision,
  34072. updatable: updatable
  34073. };
  34074. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34075. };
  34076. /**
  34077. * Creates a ground mesh from a height map.
  34078. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34079. * Please consider using the same method from the MeshBuilder class instead.
  34080. * The parameter `url` sets the URL of the height map image resource.
  34081. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34082. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34083. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34084. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34085. * 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).
  34086. * This function is passed the newly built mesh :
  34087. * ```javascript
  34088. * function(mesh) { // do things
  34089. * return; }
  34090. * ```
  34091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34092. */
  34093. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34094. var options = {
  34095. width: width,
  34096. height: height,
  34097. subdivisions: subdivisions,
  34098. minHeight: minHeight,
  34099. maxHeight: maxHeight,
  34100. updatable: updatable,
  34101. onReady: onReady
  34102. };
  34103. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34104. };
  34105. /**
  34106. * Creates a tube mesh.
  34107. * 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.
  34108. * Please consider using the same method from the MeshBuilder class instead.
  34109. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34110. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34111. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34112. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34113. * 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.
  34114. * It must return a radius value (positive float) :
  34115. * ```javascript
  34116. * var radiusFunction = function(i, distance) {
  34117. * // do things
  34118. * return radius; }
  34119. * ```
  34120. * 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
  34121. * 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
  34122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34123. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34125. */
  34126. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34127. var options = {
  34128. path: path,
  34129. radius: radius,
  34130. tessellation: tessellation,
  34131. radiusFunction: radiusFunction,
  34132. arc: 1,
  34133. cap: cap,
  34134. updatable: updatable,
  34135. sideOrientation: sideOrientation,
  34136. instance: instance
  34137. };
  34138. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34139. };
  34140. /**
  34141. * Creates a polyhedron mesh.
  34142. * Please consider using the same method from the MeshBuilder class instead.
  34143. * 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
  34144. * to choose the wanted type.
  34145. * The parameter `size` (positive float, default 1) sets the polygon size.
  34146. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34147. * 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`.
  34148. * 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
  34149. * 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)`).
  34150. * 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
  34151. * 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.
  34152. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34153. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34155. */
  34156. Mesh.CreatePolyhedron = function (name, options, scene) {
  34157. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34158. };
  34159. /**
  34160. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34161. * Please consider using the same method from the MeshBuilder class instead.
  34162. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34163. * 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`).
  34164. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34165. * 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.
  34166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34167. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34169. */
  34170. Mesh.CreateIcoSphere = function (name, options, scene) {
  34171. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34172. };
  34173. /**
  34174. * Creates a decal mesh.
  34175. * Please consider using the same method from the MeshBuilder class instead.
  34176. * 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.
  34177. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34178. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34179. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34180. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34181. */
  34182. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34183. var options = {
  34184. position: position,
  34185. normal: normal,
  34186. size: size,
  34187. angle: angle
  34188. };
  34189. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34190. };
  34191. // Skeletons
  34192. /**
  34193. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34194. */
  34195. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34196. if (!this._sourcePositions) {
  34197. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34198. if (!source) {
  34199. return this._sourcePositions;
  34200. }
  34201. this._sourcePositions = new Float32Array(source);
  34202. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34203. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34204. }
  34205. }
  34206. return this._sourcePositions;
  34207. };
  34208. /**
  34209. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34210. */
  34211. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34212. if (!this._sourceNormals) {
  34213. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34214. if (!source) {
  34215. return this._sourceNormals;
  34216. }
  34217. this._sourceNormals = new Float32Array(source);
  34218. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34219. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34220. }
  34221. }
  34222. return this._sourceNormals;
  34223. };
  34224. /**
  34225. * Updates the vertex buffer by applying transformation from the bones.
  34226. * Returns the Mesh.
  34227. *
  34228. * @param {skeleton} skeleton to apply
  34229. */
  34230. Mesh.prototype.applySkeleton = function (skeleton) {
  34231. if (!this.geometry) {
  34232. return this;
  34233. }
  34234. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34235. return this;
  34236. }
  34237. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34238. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34239. return this;
  34240. }
  34241. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34242. return this;
  34243. }
  34244. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34245. return this;
  34246. }
  34247. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34248. return this;
  34249. }
  34250. if (!this._sourcePositions) {
  34251. var submeshes = this.subMeshes.slice();
  34252. this.setPositionsForCPUSkinning();
  34253. this.subMeshes = submeshes;
  34254. }
  34255. if (!this._sourceNormals) {
  34256. this.setNormalsForCPUSkinning();
  34257. }
  34258. // positionsData checks for not being Float32Array will only pass at most once
  34259. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34260. if (!positionsData) {
  34261. return this;
  34262. }
  34263. if (!(positionsData instanceof Float32Array)) {
  34264. positionsData = new Float32Array(positionsData);
  34265. }
  34266. // normalsData checks for not being Float32Array will only pass at most once
  34267. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34268. if (!normalsData) {
  34269. return this;
  34270. }
  34271. if (!(normalsData instanceof Float32Array)) {
  34272. normalsData = new Float32Array(normalsData);
  34273. }
  34274. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34275. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34276. if (!matricesWeightsData || !matricesIndicesData) {
  34277. return this;
  34278. }
  34279. var needExtras = this.numBoneInfluencers > 4;
  34280. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34281. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34282. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34283. var tempVector3 = BABYLON.Vector3.Zero();
  34284. var finalMatrix = new BABYLON.Matrix();
  34285. var tempMatrix = new BABYLON.Matrix();
  34286. var matWeightIdx = 0;
  34287. var inf;
  34288. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34289. var weight;
  34290. for (inf = 0; inf < 4; inf++) {
  34291. weight = matricesWeightsData[matWeightIdx + inf];
  34292. if (weight > 0) {
  34293. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34294. finalMatrix.addToSelf(tempMatrix);
  34295. }
  34296. else
  34297. break;
  34298. }
  34299. if (needExtras) {
  34300. for (inf = 0; inf < 4; inf++) {
  34301. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34302. if (weight > 0) {
  34303. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34304. finalMatrix.addToSelf(tempMatrix);
  34305. }
  34306. else
  34307. break;
  34308. }
  34309. }
  34310. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34311. tempVector3.toArray(positionsData, index);
  34312. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34313. tempVector3.toArray(normalsData, index);
  34314. finalMatrix.reset();
  34315. }
  34316. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34317. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34318. return this;
  34319. };
  34320. // Tools
  34321. /**
  34322. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34323. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34324. */
  34325. Mesh.MinMax = function (meshes) {
  34326. var minVector = null;
  34327. var maxVector = null;
  34328. meshes.forEach(function (mesh, index, array) {
  34329. var boundingInfo = mesh.getBoundingInfo();
  34330. var boundingBox = boundingInfo.boundingBox;
  34331. if (!minVector || !maxVector) {
  34332. minVector = boundingBox.minimumWorld;
  34333. maxVector = boundingBox.maximumWorld;
  34334. }
  34335. else {
  34336. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34337. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34338. }
  34339. });
  34340. if (!minVector || !maxVector) {
  34341. return {
  34342. min: BABYLON.Vector3.Zero(),
  34343. max: BABYLON.Vector3.Zero()
  34344. };
  34345. }
  34346. return {
  34347. min: minVector,
  34348. max: maxVector
  34349. };
  34350. };
  34351. /**
  34352. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34353. */
  34354. Mesh.Center = function (meshesOrMinMaxVector) {
  34355. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34356. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34357. };
  34358. /**
  34359. * Merge the array of meshes into a single mesh for performance reasons.
  34360. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34361. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34362. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34363. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34364. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34365. */
  34366. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34367. if (disposeSource === void 0) { disposeSource = true; }
  34368. var index;
  34369. if (!allow32BitsIndices) {
  34370. var totalVertices = 0;
  34371. // Counting vertices
  34372. for (index = 0; index < meshes.length; index++) {
  34373. if (meshes[index]) {
  34374. totalVertices += meshes[index].getTotalVertices();
  34375. if (totalVertices > 65536) {
  34376. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34377. return null;
  34378. }
  34379. }
  34380. }
  34381. }
  34382. // Merge
  34383. var vertexData = null;
  34384. var otherVertexData;
  34385. var indiceArray = new Array();
  34386. var source = null;
  34387. for (index = 0; index < meshes.length; index++) {
  34388. if (meshes[index]) {
  34389. meshes[index].computeWorldMatrix(true);
  34390. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34391. otherVertexData.transform(meshes[index].getWorldMatrix());
  34392. if (vertexData) {
  34393. vertexData.merge(otherVertexData);
  34394. }
  34395. else {
  34396. vertexData = otherVertexData;
  34397. source = meshes[index];
  34398. }
  34399. if (subdivideWithSubMeshes) {
  34400. indiceArray.push(meshes[index].getTotalIndices());
  34401. }
  34402. }
  34403. }
  34404. source = source;
  34405. if (!meshSubclass) {
  34406. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34407. }
  34408. vertexData.applyToMesh(meshSubclass);
  34409. // Setting properties
  34410. meshSubclass.material = source.material;
  34411. meshSubclass.checkCollisions = source.checkCollisions;
  34412. // Cleaning
  34413. if (disposeSource) {
  34414. for (index = 0; index < meshes.length; index++) {
  34415. if (meshes[index]) {
  34416. meshes[index].dispose();
  34417. }
  34418. }
  34419. }
  34420. // Subdivide
  34421. if (subdivideWithSubMeshes) {
  34422. //-- removal of global submesh
  34423. meshSubclass.releaseSubMeshes();
  34424. index = 0;
  34425. var offset = 0;
  34426. //-- apply subdivision according to index table
  34427. while (index < indiceArray.length) {
  34428. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34429. offset += indiceArray[index];
  34430. index++;
  34431. }
  34432. }
  34433. return meshSubclass;
  34434. };
  34435. // Consts
  34436. Mesh._FRONTSIDE = 0;
  34437. Mesh._BACKSIDE = 1;
  34438. Mesh._DOUBLESIDE = 2;
  34439. Mesh._DEFAULTSIDE = 0;
  34440. Mesh._NO_CAP = 0;
  34441. Mesh._CAP_START = 1;
  34442. Mesh._CAP_END = 2;
  34443. Mesh._CAP_ALL = 3;
  34444. return Mesh;
  34445. }(BABYLON.AbstractMesh));
  34446. BABYLON.Mesh = Mesh;
  34447. })(BABYLON || (BABYLON = {}));
  34448. //# sourceMappingURL=babylon.mesh.js.map
  34449. var BABYLON;
  34450. (function (BABYLON) {
  34451. var BaseSubMesh = /** @class */ (function () {
  34452. function BaseSubMesh() {
  34453. }
  34454. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34455. get: function () {
  34456. return this._materialEffect;
  34457. },
  34458. enumerable: true,
  34459. configurable: true
  34460. });
  34461. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34462. if (defines === void 0) { defines = null; }
  34463. if (this._materialEffect === effect) {
  34464. if (!effect) {
  34465. this._materialDefines = null;
  34466. }
  34467. return;
  34468. }
  34469. this._materialDefines = defines;
  34470. this._materialEffect = effect;
  34471. };
  34472. return BaseSubMesh;
  34473. }());
  34474. BABYLON.BaseSubMesh = BaseSubMesh;
  34475. var SubMesh = /** @class */ (function (_super) {
  34476. __extends(SubMesh, _super);
  34477. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34478. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34479. var _this = _super.call(this) || this;
  34480. _this.materialIndex = materialIndex;
  34481. _this.verticesStart = verticesStart;
  34482. _this.verticesCount = verticesCount;
  34483. _this.indexStart = indexStart;
  34484. _this.indexCount = indexCount;
  34485. _this._renderId = 0;
  34486. _this._mesh = mesh;
  34487. _this._renderingMesh = renderingMesh || mesh;
  34488. mesh.subMeshes.push(_this);
  34489. _this._trianglePlanes = [];
  34490. _this._id = mesh.subMeshes.length - 1;
  34491. if (createBoundingBox) {
  34492. _this.refreshBoundingInfo();
  34493. mesh.computeWorldMatrix(true);
  34494. }
  34495. return _this;
  34496. }
  34497. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34498. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34499. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34500. };
  34501. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34502. get: function () {
  34503. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34504. },
  34505. enumerable: true,
  34506. configurable: true
  34507. });
  34508. /**
  34509. * Returns the submesh BoudingInfo object.
  34510. */
  34511. SubMesh.prototype.getBoundingInfo = function () {
  34512. if (this.IsGlobal) {
  34513. return this._mesh.getBoundingInfo();
  34514. }
  34515. return this._boundingInfo;
  34516. };
  34517. /**
  34518. * Sets the submesh BoundingInfo.
  34519. * Return the SubMesh.
  34520. */
  34521. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34522. this._boundingInfo = boundingInfo;
  34523. return this;
  34524. };
  34525. /**
  34526. * Returns the mesh of the current submesh.
  34527. */
  34528. SubMesh.prototype.getMesh = function () {
  34529. return this._mesh;
  34530. };
  34531. /**
  34532. * Returns the rendering mesh of the submesh.
  34533. */
  34534. SubMesh.prototype.getRenderingMesh = function () {
  34535. return this._renderingMesh;
  34536. };
  34537. /**
  34538. * Returns the submesh material.
  34539. */
  34540. SubMesh.prototype.getMaterial = function () {
  34541. var rootMaterial = this._renderingMesh.material;
  34542. if (rootMaterial === null || rootMaterial === undefined) {
  34543. return this._mesh.getScene().defaultMaterial;
  34544. }
  34545. else if (rootMaterial.getSubMaterial) {
  34546. var multiMaterial = rootMaterial;
  34547. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34548. if (this._currentMaterial !== effectiveMaterial) {
  34549. this._currentMaterial = effectiveMaterial;
  34550. this._materialDefines = null;
  34551. }
  34552. return effectiveMaterial;
  34553. }
  34554. return rootMaterial;
  34555. };
  34556. // Methods
  34557. /**
  34558. * Sets a new updated BoundingInfo object to the submesh.
  34559. * Returns the SubMesh.
  34560. */
  34561. SubMesh.prototype.refreshBoundingInfo = function () {
  34562. this._lastColliderWorldVertices = null;
  34563. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34564. return this;
  34565. }
  34566. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34567. if (!data) {
  34568. this._boundingInfo = this._mesh.getBoundingInfo();
  34569. return this;
  34570. }
  34571. var indices = this._renderingMesh.getIndices();
  34572. var extend;
  34573. //is this the only submesh?
  34574. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34575. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34576. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34577. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34578. }
  34579. else {
  34580. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34581. }
  34582. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34583. return this;
  34584. };
  34585. SubMesh.prototype._checkCollision = function (collider) {
  34586. var boundingInfo = this.getBoundingInfo();
  34587. return boundingInfo._checkCollision(collider);
  34588. };
  34589. /**
  34590. * Updates the submesh BoundingInfo.
  34591. * Returns the Submesh.
  34592. */
  34593. SubMesh.prototype.updateBoundingInfo = function (world) {
  34594. var boundingInfo = this.getBoundingInfo();
  34595. if (!boundingInfo) {
  34596. this.refreshBoundingInfo();
  34597. boundingInfo = this.getBoundingInfo();
  34598. }
  34599. boundingInfo.update(world);
  34600. return this;
  34601. };
  34602. /**
  34603. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34604. * Boolean returned.
  34605. */
  34606. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34607. var boundingInfo = this.getBoundingInfo();
  34608. if (!boundingInfo) {
  34609. return false;
  34610. }
  34611. return boundingInfo.isInFrustum(frustumPlanes);
  34612. };
  34613. /**
  34614. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34615. * Boolean returned.
  34616. */
  34617. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34618. var boundingInfo = this.getBoundingInfo();
  34619. if (!boundingInfo) {
  34620. return false;
  34621. }
  34622. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34623. };
  34624. /**
  34625. * Renders the submesh.
  34626. * Returns it.
  34627. */
  34628. SubMesh.prototype.render = function (enableAlphaMode) {
  34629. this._renderingMesh.render(this, enableAlphaMode);
  34630. return this;
  34631. };
  34632. /**
  34633. * Returns a new Index Buffer.
  34634. * Type returned : WebGLBuffer.
  34635. */
  34636. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34637. if (!this._linesIndexBuffer) {
  34638. var linesIndices = [];
  34639. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34640. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34641. }
  34642. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34643. this.linesIndexCount = linesIndices.length;
  34644. }
  34645. return this._linesIndexBuffer;
  34646. };
  34647. /**
  34648. * True is the passed Ray intersects the submesh bounding box.
  34649. * Boolean returned.
  34650. */
  34651. SubMesh.prototype.canIntersects = function (ray) {
  34652. var boundingInfo = this.getBoundingInfo();
  34653. if (!boundingInfo) {
  34654. return false;
  34655. }
  34656. return ray.intersectsBox(boundingInfo.boundingBox);
  34657. };
  34658. /**
  34659. * Returns an object IntersectionInfo.
  34660. */
  34661. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34662. var intersectInfo = null;
  34663. var material = this.getMaterial();
  34664. if (!material) {
  34665. return null;
  34666. }
  34667. switch (material.fillMode) {
  34668. case BABYLON.Material.PointListDrawMode:
  34669. case BABYLON.Material.LineListDrawMode:
  34670. case BABYLON.Material.LineLoopDrawMode:
  34671. case BABYLON.Material.LineStripDrawMode:
  34672. case BABYLON.Material.TriangleFanDrawMode:
  34673. case BABYLON.Material.TriangleStripDrawMode:
  34674. return null;
  34675. }
  34676. // LineMesh first as it's also a Mesh...
  34677. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34678. var lineMesh = this._mesh;
  34679. // Line test
  34680. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34681. var p0 = positions[indices[index]];
  34682. var p1 = positions[indices[index + 1]];
  34683. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34684. if (length < 0) {
  34685. continue;
  34686. }
  34687. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34688. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34689. if (fastCheck) {
  34690. break;
  34691. }
  34692. }
  34693. }
  34694. }
  34695. else {
  34696. // Triangles test
  34697. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34698. var p0 = positions[indices[index]];
  34699. var p1 = positions[indices[index + 1]];
  34700. var p2 = positions[indices[index + 2]];
  34701. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34702. if (currentIntersectInfo) {
  34703. if (currentIntersectInfo.distance < 0) {
  34704. continue;
  34705. }
  34706. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34707. intersectInfo = currentIntersectInfo;
  34708. intersectInfo.faceId = index / 3;
  34709. if (fastCheck) {
  34710. break;
  34711. }
  34712. }
  34713. }
  34714. }
  34715. }
  34716. return intersectInfo;
  34717. };
  34718. SubMesh.prototype._rebuild = function () {
  34719. if (this._linesIndexBuffer) {
  34720. this._linesIndexBuffer = null;
  34721. }
  34722. };
  34723. // Clone
  34724. /**
  34725. * Creates a new Submesh from the passed Mesh.
  34726. */
  34727. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34728. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34729. if (!this.IsGlobal) {
  34730. var boundingInfo = this.getBoundingInfo();
  34731. if (!boundingInfo) {
  34732. return result;
  34733. }
  34734. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34735. }
  34736. return result;
  34737. };
  34738. // Dispose
  34739. /**
  34740. * Disposes the Submesh.
  34741. * Returns nothing.
  34742. */
  34743. SubMesh.prototype.dispose = function () {
  34744. if (this._linesIndexBuffer) {
  34745. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34746. this._linesIndexBuffer = null;
  34747. }
  34748. // Remove from mesh
  34749. var index = this._mesh.subMeshes.indexOf(this);
  34750. this._mesh.subMeshes.splice(index, 1);
  34751. };
  34752. // Statics
  34753. /**
  34754. * Creates a new Submesh from the passed parameters :
  34755. * - materialIndex (integer) : the index of the main mesh material.
  34756. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34757. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34758. * - mesh (Mesh) : the main mesh to create the submesh from.
  34759. * - renderingMesh (optional Mesh) : rendering mesh.
  34760. */
  34761. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34762. var minVertexIndex = Number.MAX_VALUE;
  34763. var maxVertexIndex = -Number.MAX_VALUE;
  34764. renderingMesh = (renderingMesh || mesh);
  34765. var indices = renderingMesh.getIndices();
  34766. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34767. var vertexIndex = indices[index];
  34768. if (vertexIndex < minVertexIndex)
  34769. minVertexIndex = vertexIndex;
  34770. if (vertexIndex > maxVertexIndex)
  34771. maxVertexIndex = vertexIndex;
  34772. }
  34773. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34774. };
  34775. return SubMesh;
  34776. }(BaseSubMesh));
  34777. BABYLON.SubMesh = SubMesh;
  34778. })(BABYLON || (BABYLON = {}));
  34779. //# sourceMappingURL=babylon.subMesh.js.map
  34780. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34781. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34782. s = arguments[i];
  34783. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34784. t[p] = s[p];
  34785. }
  34786. return t;
  34787. };
  34788. var BABYLON;
  34789. (function (BABYLON) {
  34790. /**
  34791. * Manages the defines for the Material
  34792. */
  34793. var MaterialDefines = /** @class */ (function () {
  34794. function MaterialDefines() {
  34795. this._isDirty = true;
  34796. /** @hidden */
  34797. this._areLightsDirty = true;
  34798. /** @hidden */
  34799. this._areAttributesDirty = true;
  34800. /** @hidden */
  34801. this._areTexturesDirty = true;
  34802. /** @hidden */
  34803. this._areFresnelDirty = true;
  34804. /** @hidden */
  34805. this._areMiscDirty = true;
  34806. /** @hidden */
  34807. this._areImageProcessingDirty = true;
  34808. /** @hidden */
  34809. this._normals = false;
  34810. /** @hidden */
  34811. this._uvs = false;
  34812. /** @hidden */
  34813. this._needNormals = false;
  34814. /** @hidden */
  34815. this._needUVs = false;
  34816. }
  34817. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34818. /**
  34819. * Specifies if the material needs to be re-calculated
  34820. */
  34821. get: function () {
  34822. return this._isDirty;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. /**
  34828. * Marks the material to indicate that it has been re-calculated
  34829. */
  34830. MaterialDefines.prototype.markAsProcessed = function () {
  34831. this._isDirty = false;
  34832. this._areAttributesDirty = false;
  34833. this._areTexturesDirty = false;
  34834. this._areFresnelDirty = false;
  34835. this._areLightsDirty = false;
  34836. this._areMiscDirty = false;
  34837. this._areImageProcessingDirty = false;
  34838. };
  34839. /**
  34840. * Marks the material to indicate that it needs to be re-calculated
  34841. */
  34842. MaterialDefines.prototype.markAsUnprocessed = function () {
  34843. this._isDirty = true;
  34844. };
  34845. /**
  34846. * Marks the material to indicate all of its defines need to be re-calculated
  34847. */
  34848. MaterialDefines.prototype.markAllAsDirty = function () {
  34849. this._areTexturesDirty = true;
  34850. this._areAttributesDirty = true;
  34851. this._areLightsDirty = true;
  34852. this._areFresnelDirty = true;
  34853. this._areMiscDirty = true;
  34854. this._areImageProcessingDirty = true;
  34855. this._isDirty = true;
  34856. };
  34857. /**
  34858. * Marks the material to indicate that image processing needs to be re-calculated
  34859. */
  34860. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34861. this._areImageProcessingDirty = true;
  34862. this._isDirty = true;
  34863. };
  34864. /**
  34865. * Marks the material to indicate the lights need to be re-calculated
  34866. */
  34867. MaterialDefines.prototype.markAsLightDirty = function () {
  34868. this._areLightsDirty = true;
  34869. this._isDirty = true;
  34870. };
  34871. /**
  34872. * Marks the attribute state as changed
  34873. */
  34874. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34875. this._areAttributesDirty = true;
  34876. this._isDirty = true;
  34877. };
  34878. /**
  34879. * Marks the texture state as changed
  34880. */
  34881. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34882. this._areTexturesDirty = true;
  34883. this._isDirty = true;
  34884. };
  34885. /**
  34886. * Marks the fresnel state as changed
  34887. */
  34888. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34889. this._areFresnelDirty = true;
  34890. this._isDirty = true;
  34891. };
  34892. /**
  34893. * Marks the misc state as changed
  34894. */
  34895. MaterialDefines.prototype.markAsMiscDirty = function () {
  34896. this._areMiscDirty = true;
  34897. this._isDirty = true;
  34898. };
  34899. /**
  34900. * Rebuilds the material defines
  34901. */
  34902. MaterialDefines.prototype.rebuild = function () {
  34903. if (this._keys) {
  34904. delete this._keys;
  34905. }
  34906. this._keys = [];
  34907. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34908. var key = _a[_i];
  34909. if (key[0] === "_") {
  34910. continue;
  34911. }
  34912. this._keys.push(key);
  34913. }
  34914. };
  34915. /**
  34916. * Specifies if two material defines are equal
  34917. * @param other - A material define instance to compare to
  34918. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34919. */
  34920. MaterialDefines.prototype.isEqual = function (other) {
  34921. if (this._keys.length !== other._keys.length) {
  34922. return false;
  34923. }
  34924. for (var index = 0; index < this._keys.length; index++) {
  34925. var prop = this._keys[index];
  34926. if (this[prop] !== other[prop]) {
  34927. return false;
  34928. }
  34929. }
  34930. return true;
  34931. };
  34932. /**
  34933. * Clones this instance's defines to another instance
  34934. * @param other - material defines to clone values to
  34935. */
  34936. MaterialDefines.prototype.cloneTo = function (other) {
  34937. if (this._keys.length !== other._keys.length) {
  34938. other._keys = this._keys.slice(0);
  34939. }
  34940. for (var index = 0; index < this._keys.length; index++) {
  34941. var prop = this._keys[index];
  34942. other[prop] = this[prop];
  34943. }
  34944. };
  34945. /**
  34946. * Resets the material define values
  34947. */
  34948. MaterialDefines.prototype.reset = function () {
  34949. for (var index = 0; index < this._keys.length; index++) {
  34950. var prop = this._keys[index];
  34951. var type = typeof this[prop];
  34952. switch (type) {
  34953. case "number":
  34954. this[prop] = 0;
  34955. break;
  34956. case "string":
  34957. this[prop] = "";
  34958. break;
  34959. default:
  34960. this[prop] = false;
  34961. break;
  34962. }
  34963. }
  34964. };
  34965. /**
  34966. * Converts the material define values to a string
  34967. * @returns - String of material define information
  34968. */
  34969. MaterialDefines.prototype.toString = function () {
  34970. var result = "";
  34971. for (var index = 0; index < this._keys.length; index++) {
  34972. var prop = this._keys[index];
  34973. var value = this[prop];
  34974. var type = typeof value;
  34975. switch (type) {
  34976. case "number":
  34977. case "string":
  34978. result += "#define " + prop + " " + value + "\n";
  34979. break;
  34980. default:
  34981. if (value) {
  34982. result += "#define " + prop + "\n";
  34983. }
  34984. break;
  34985. }
  34986. }
  34987. return result;
  34988. };
  34989. return MaterialDefines;
  34990. }());
  34991. BABYLON.MaterialDefines = MaterialDefines;
  34992. /**
  34993. * Base class for the main features of a material in Babylon.js
  34994. */
  34995. var Material = /** @class */ (function () {
  34996. /**
  34997. * Creates a material instance
  34998. * @param name defines the name of the material
  34999. * @param scene defines the scene to reference
  35000. * @param doNotAdd specifies if the material should be added to the scene
  35001. */
  35002. function Material(name, scene, doNotAdd) {
  35003. /**
  35004. * Specifies if the ready state should be checked on each call
  35005. */
  35006. this.checkReadyOnEveryCall = false;
  35007. /**
  35008. * Specifies if the ready state should be checked once
  35009. */
  35010. this.checkReadyOnlyOnce = false;
  35011. /**
  35012. * The state of the material
  35013. */
  35014. this.state = "";
  35015. /**
  35016. * The alpha value of the material
  35017. */
  35018. this._alpha = 1.0;
  35019. /**
  35020. * Specifies if back face culling is enabled
  35021. */
  35022. this._backFaceCulling = true;
  35023. /**
  35024. * Specifies if the material should be serialized
  35025. */
  35026. this.doNotSerialize = false;
  35027. /**
  35028. * Specifies if the effect should be stored on sub meshes
  35029. */
  35030. this.storeEffectOnSubMeshes = false;
  35031. /**
  35032. * An event triggered when the material is disposed
  35033. */
  35034. this.onDisposeObservable = new BABYLON.Observable();
  35035. /**
  35036. * An event triggered when the material is bound
  35037. */
  35038. this.onBindObservable = new BABYLON.Observable();
  35039. /**
  35040. * An event triggered when the material is unbound
  35041. */
  35042. this.onUnBindObservable = new BABYLON.Observable();
  35043. /**
  35044. * Stores the value of the alpha mode
  35045. */
  35046. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35047. /**
  35048. * Stores the state of the need depth pre-pass value
  35049. */
  35050. this._needDepthPrePass = false;
  35051. /**
  35052. * Specifies if depth writing should be disabled
  35053. */
  35054. this.disableDepthWrite = false;
  35055. /**
  35056. * Specifies if depth writing should be forced
  35057. */
  35058. this.forceDepthWrite = false;
  35059. /**
  35060. * Specifies if there should be a separate pass for culling
  35061. */
  35062. this.separateCullingPass = false;
  35063. /**
  35064. * Stores the state specifing if fog should be enabled
  35065. */
  35066. this._fogEnabled = true;
  35067. /**
  35068. * Stores the size of points
  35069. */
  35070. this.pointSize = 1.0;
  35071. /**
  35072. * Stores the z offset value
  35073. */
  35074. this.zOffset = 0;
  35075. /**
  35076. * Specifies if the material was previously ready
  35077. */
  35078. this._wasPreviouslyReady = false;
  35079. /**
  35080. * Stores the fill mode state
  35081. */
  35082. this._fillMode = Material.TriangleFillMode;
  35083. this.name = name;
  35084. this.id = name || BABYLON.Tools.RandomId();
  35085. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35086. this.uniqueId = this._scene.getUniqueId();
  35087. if (this._scene.useRightHandedSystem) {
  35088. this.sideOrientation = Material.ClockWiseSideOrientation;
  35089. }
  35090. else {
  35091. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35092. }
  35093. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35094. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35095. if (!doNotAdd) {
  35096. this._scene.materials.push(this);
  35097. }
  35098. }
  35099. Object.defineProperty(Material, "TriangleFillMode", {
  35100. /**
  35101. * Returns the triangle fill mode
  35102. */
  35103. get: function () {
  35104. return Material._TriangleFillMode;
  35105. },
  35106. enumerable: true,
  35107. configurable: true
  35108. });
  35109. Object.defineProperty(Material, "WireFrameFillMode", {
  35110. /**
  35111. * Returns the wireframe mode
  35112. */
  35113. get: function () {
  35114. return Material._WireFrameFillMode;
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. Object.defineProperty(Material, "PointFillMode", {
  35120. /**
  35121. * Returns the point fill mode
  35122. */
  35123. get: function () {
  35124. return Material._PointFillMode;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(Material, "PointListDrawMode", {
  35130. /**
  35131. * Returns the point list draw mode
  35132. */
  35133. get: function () {
  35134. return Material._PointListDrawMode;
  35135. },
  35136. enumerable: true,
  35137. configurable: true
  35138. });
  35139. Object.defineProperty(Material, "LineListDrawMode", {
  35140. /**
  35141. * Returns the line list draw mode
  35142. */
  35143. get: function () {
  35144. return Material._LineListDrawMode;
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(Material, "LineLoopDrawMode", {
  35150. /**
  35151. * Returns the line loop draw mode
  35152. */
  35153. get: function () {
  35154. return Material._LineLoopDrawMode;
  35155. },
  35156. enumerable: true,
  35157. configurable: true
  35158. });
  35159. Object.defineProperty(Material, "LineStripDrawMode", {
  35160. /**
  35161. * Returns the line strip draw mode
  35162. */
  35163. get: function () {
  35164. return Material._LineStripDrawMode;
  35165. },
  35166. enumerable: true,
  35167. configurable: true
  35168. });
  35169. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35170. /**
  35171. * Returns the triangle strip draw mode
  35172. */
  35173. get: function () {
  35174. return Material._TriangleStripDrawMode;
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35180. /**
  35181. * Returns the triangle fan draw mode
  35182. */
  35183. get: function () {
  35184. return Material._TriangleFanDrawMode;
  35185. },
  35186. enumerable: true,
  35187. configurable: true
  35188. });
  35189. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35190. /**
  35191. * Returns the clock-wise side orientation
  35192. */
  35193. get: function () {
  35194. return Material._ClockWiseSideOrientation;
  35195. },
  35196. enumerable: true,
  35197. configurable: true
  35198. });
  35199. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35200. /**
  35201. * Returns the counter clock-wise side orientation
  35202. */
  35203. get: function () {
  35204. return Material._CounterClockWiseSideOrientation;
  35205. },
  35206. enumerable: true,
  35207. configurable: true
  35208. });
  35209. Object.defineProperty(Material, "TextureDirtyFlag", {
  35210. /**
  35211. * Returns the dirty texture flag value
  35212. */
  35213. get: function () {
  35214. return Material._TextureDirtyFlag;
  35215. },
  35216. enumerable: true,
  35217. configurable: true
  35218. });
  35219. Object.defineProperty(Material, "LightDirtyFlag", {
  35220. /**
  35221. * Returns the dirty light flag value
  35222. */
  35223. get: function () {
  35224. return Material._LightDirtyFlag;
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35230. /**
  35231. * Returns the dirty fresnel flag value
  35232. */
  35233. get: function () {
  35234. return Material._FresnelDirtyFlag;
  35235. },
  35236. enumerable: true,
  35237. configurable: true
  35238. });
  35239. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35240. /**
  35241. * Returns the dirty attributes flag value
  35242. */
  35243. get: function () {
  35244. return Material._AttributesDirtyFlag;
  35245. },
  35246. enumerable: true,
  35247. configurable: true
  35248. });
  35249. Object.defineProperty(Material, "MiscDirtyFlag", {
  35250. /**
  35251. * Returns the dirty misc flag value
  35252. */
  35253. get: function () {
  35254. return Material._MiscDirtyFlag;
  35255. },
  35256. enumerable: true,
  35257. configurable: true
  35258. });
  35259. Object.defineProperty(Material.prototype, "alpha", {
  35260. /**
  35261. * Gets the alpha value of the material
  35262. */
  35263. get: function () {
  35264. return this._alpha;
  35265. },
  35266. /**
  35267. * Sets the alpha value of the material
  35268. */
  35269. set: function (value) {
  35270. if (this._alpha === value) {
  35271. return;
  35272. }
  35273. this._alpha = value;
  35274. this.markAsDirty(Material.MiscDirtyFlag);
  35275. },
  35276. enumerable: true,
  35277. configurable: true
  35278. });
  35279. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35280. /**
  35281. * Gets the back-face culling state
  35282. */
  35283. get: function () {
  35284. return this._backFaceCulling;
  35285. },
  35286. /**
  35287. * Sets the back-face culling state
  35288. */
  35289. set: function (value) {
  35290. if (this._backFaceCulling === value) {
  35291. return;
  35292. }
  35293. this._backFaceCulling = value;
  35294. this.markAsDirty(Material.TextureDirtyFlag);
  35295. },
  35296. enumerable: true,
  35297. configurable: true
  35298. });
  35299. Object.defineProperty(Material.prototype, "onDispose", {
  35300. /**
  35301. * Called during a dispose event
  35302. */
  35303. set: function (callback) {
  35304. if (this._onDisposeObserver) {
  35305. this.onDisposeObservable.remove(this._onDisposeObserver);
  35306. }
  35307. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35308. },
  35309. enumerable: true,
  35310. configurable: true
  35311. });
  35312. Object.defineProperty(Material.prototype, "onBind", {
  35313. /**
  35314. * Called during a bind event
  35315. */
  35316. set: function (callback) {
  35317. if (this._onBindObserver) {
  35318. this.onBindObservable.remove(this._onBindObserver);
  35319. }
  35320. this._onBindObserver = this.onBindObservable.add(callback);
  35321. },
  35322. enumerable: true,
  35323. configurable: true
  35324. });
  35325. Object.defineProperty(Material.prototype, "alphaMode", {
  35326. /**
  35327. * Gets the value of the alpha mode
  35328. */
  35329. get: function () {
  35330. return this._alphaMode;
  35331. },
  35332. /**
  35333. * Sets the value of the alpha mode.
  35334. *
  35335. * | Value | Type | Description |
  35336. * | --- | --- | --- |
  35337. * | 0 | ALPHA_DISABLE | |
  35338. * | 1 | ALPHA_ADD | |
  35339. * | 2 | ALPHA_COMBINE | |
  35340. * | 3 | ALPHA_SUBTRACT | |
  35341. * | 4 | ALPHA_MULTIPLY | |
  35342. * | 5 | ALPHA_MAXIMIZED | |
  35343. * | 6 | ALPHA_ONEONE | |
  35344. * | 7 | ALPHA_PREMULTIPLIED | |
  35345. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35346. * | 9 | ALPHA_INTERPOLATE | |
  35347. * | 10 | ALPHA_SCREENMODE | |
  35348. *
  35349. */
  35350. set: function (value) {
  35351. if (this._alphaMode === value) {
  35352. return;
  35353. }
  35354. this._alphaMode = value;
  35355. this.markAsDirty(Material.TextureDirtyFlag);
  35356. },
  35357. enumerable: true,
  35358. configurable: true
  35359. });
  35360. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35361. /**
  35362. * Gets the depth pre-pass value
  35363. */
  35364. get: function () {
  35365. return this._needDepthPrePass;
  35366. },
  35367. /**
  35368. * Sets the need depth pre-pass value
  35369. */
  35370. set: function (value) {
  35371. if (this._needDepthPrePass === value) {
  35372. return;
  35373. }
  35374. this._needDepthPrePass = value;
  35375. if (this._needDepthPrePass) {
  35376. this.checkReadyOnEveryCall = true;
  35377. }
  35378. },
  35379. enumerable: true,
  35380. configurable: true
  35381. });
  35382. Object.defineProperty(Material.prototype, "fogEnabled", {
  35383. /**
  35384. * Gets the value of the fog enabled state
  35385. */
  35386. get: function () {
  35387. return this._fogEnabled;
  35388. },
  35389. /**
  35390. * Sets the state for enabling fog
  35391. */
  35392. set: function (value) {
  35393. if (this._fogEnabled === value) {
  35394. return;
  35395. }
  35396. this._fogEnabled = value;
  35397. this.markAsDirty(Material.MiscDirtyFlag);
  35398. },
  35399. enumerable: true,
  35400. configurable: true
  35401. });
  35402. Object.defineProperty(Material.prototype, "wireframe", {
  35403. /**
  35404. * Gets a value specifying if wireframe mode is enabled
  35405. */
  35406. get: function () {
  35407. switch (this._fillMode) {
  35408. case Material.WireFrameFillMode:
  35409. case Material.LineListDrawMode:
  35410. case Material.LineLoopDrawMode:
  35411. case Material.LineStripDrawMode:
  35412. return true;
  35413. }
  35414. return this._scene.forceWireframe;
  35415. },
  35416. /**
  35417. * Sets the state of wireframe mode
  35418. */
  35419. set: function (value) {
  35420. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35421. },
  35422. enumerable: true,
  35423. configurable: true
  35424. });
  35425. Object.defineProperty(Material.prototype, "pointsCloud", {
  35426. /**
  35427. * Gets the value specifying if point clouds are enabled
  35428. */
  35429. get: function () {
  35430. switch (this._fillMode) {
  35431. case Material.PointFillMode:
  35432. case Material.PointListDrawMode:
  35433. return true;
  35434. }
  35435. return this._scene.forcePointsCloud;
  35436. },
  35437. /**
  35438. * Sets the state of point cloud mode
  35439. */
  35440. set: function (value) {
  35441. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35442. },
  35443. enumerable: true,
  35444. configurable: true
  35445. });
  35446. Object.defineProperty(Material.prototype, "fillMode", {
  35447. /**
  35448. * Gets the material fill mode
  35449. */
  35450. get: function () {
  35451. return this._fillMode;
  35452. },
  35453. /**
  35454. * Sets the material fill mode
  35455. */
  35456. set: function (value) {
  35457. if (this._fillMode === value) {
  35458. return;
  35459. }
  35460. this._fillMode = value;
  35461. this.markAsDirty(Material.MiscDirtyFlag);
  35462. },
  35463. enumerable: true,
  35464. configurable: true
  35465. });
  35466. /**
  35467. * Returns a string representation of the current material
  35468. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35469. * @returns a string with material information
  35470. */
  35471. Material.prototype.toString = function (fullDetails) {
  35472. var ret = "Name: " + this.name;
  35473. if (fullDetails) {
  35474. }
  35475. return ret;
  35476. };
  35477. /**
  35478. * Gets the class name of the material
  35479. * @returns a string with the class name of the material
  35480. */
  35481. Material.prototype.getClassName = function () {
  35482. return "Material";
  35483. };
  35484. Object.defineProperty(Material.prototype, "isFrozen", {
  35485. /**
  35486. * Specifies if updates for the material been locked
  35487. */
  35488. get: function () {
  35489. return this.checkReadyOnlyOnce;
  35490. },
  35491. enumerable: true,
  35492. configurable: true
  35493. });
  35494. /**
  35495. * Locks updates for the material
  35496. */
  35497. Material.prototype.freeze = function () {
  35498. this.checkReadyOnlyOnce = true;
  35499. };
  35500. /**
  35501. * Unlocks updates for the material
  35502. */
  35503. Material.prototype.unfreeze = function () {
  35504. this.checkReadyOnlyOnce = false;
  35505. };
  35506. /**
  35507. * Specifies if the material is ready to be used
  35508. * @param mesh defines the mesh to check
  35509. * @param useInstances specifies if instances should be used
  35510. * @returns a boolean indicating if the material is ready to be used
  35511. */
  35512. Material.prototype.isReady = function (mesh, useInstances) {
  35513. return true;
  35514. };
  35515. /**
  35516. * Specifies that the submesh is ready to be used
  35517. * @param mesh defines the mesh to check
  35518. * @param subMesh defines which submesh to check
  35519. * @param useInstances specifies that instances should be used
  35520. * @returns a boolean indicating that the submesh is ready or not
  35521. */
  35522. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35523. return false;
  35524. };
  35525. /**
  35526. * Returns the material effect
  35527. * @returns the effect associated with the material
  35528. */
  35529. Material.prototype.getEffect = function () {
  35530. return this._effect;
  35531. };
  35532. /**
  35533. * Returns the current scene
  35534. * @returns a Scene
  35535. */
  35536. Material.prototype.getScene = function () {
  35537. return this._scene;
  35538. };
  35539. /**
  35540. * Specifies if the material will require alpha blending
  35541. * @returns a boolean specifying if alpha blending is needed
  35542. */
  35543. Material.prototype.needAlphaBlending = function () {
  35544. return (this.alpha < 1.0);
  35545. };
  35546. /**
  35547. * Specifies if the mesh will require alpha blending
  35548. * @param mesh defines the mesh to check
  35549. * @returns a boolean specifying if alpha blending is needed for the mesh
  35550. */
  35551. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35552. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35553. };
  35554. /**
  35555. * Specifies if this material should be rendered in alpha test mode
  35556. * @returns a boolean specifying if an alpha test is needed.
  35557. */
  35558. Material.prototype.needAlphaTesting = function () {
  35559. return false;
  35560. };
  35561. /**
  35562. * Gets the texture used for the alpha test
  35563. * @returns the texture to use for alpha testing
  35564. */
  35565. Material.prototype.getAlphaTestTexture = function () {
  35566. return null;
  35567. };
  35568. /**
  35569. * Marks the material to indicate that it needs to be re-calculated
  35570. */
  35571. Material.prototype.markDirty = function () {
  35572. this._wasPreviouslyReady = false;
  35573. };
  35574. /** @hidden */
  35575. Material.prototype._preBind = function (effect, overrideOrientation) {
  35576. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35577. var engine = this._scene.getEngine();
  35578. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35579. var reverse = orientation === Material.ClockWiseSideOrientation;
  35580. engine.enableEffect(effect ? effect : this._effect);
  35581. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35582. return reverse;
  35583. };
  35584. /**
  35585. * Binds the material to the mesh
  35586. * @param world defines the world transformation matrix
  35587. * @param mesh defines the mesh to bind the material to
  35588. */
  35589. Material.prototype.bind = function (world, mesh) {
  35590. };
  35591. /**
  35592. * Binds the submesh to the material
  35593. * @param world defines the world transformation matrix
  35594. * @param mesh defines the mesh containing the submesh
  35595. * @param subMesh defines the submesh to bind the material to
  35596. */
  35597. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35598. };
  35599. /**
  35600. * Binds the world matrix to the material
  35601. * @param world defines the world transformation matrix
  35602. */
  35603. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35604. };
  35605. /**
  35606. * Binds the scene's uniform buffer to the effect.
  35607. * @param effect defines the effect to bind to the scene uniform buffer
  35608. * @param sceneUbo defines the uniform buffer storing scene data
  35609. */
  35610. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35611. sceneUbo.bindToEffect(effect, "Scene");
  35612. };
  35613. /**
  35614. * Binds the view matrix to the effect
  35615. * @param effect defines the effect to bind the view matrix to
  35616. */
  35617. Material.prototype.bindView = function (effect) {
  35618. if (!this._useUBO) {
  35619. effect.setMatrix("view", this.getScene().getViewMatrix());
  35620. }
  35621. else {
  35622. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35623. }
  35624. };
  35625. /**
  35626. * Binds the view projection matrix to the effect
  35627. * @param effect defines the effect to bind the view projection matrix to
  35628. */
  35629. Material.prototype.bindViewProjection = function (effect) {
  35630. if (!this._useUBO) {
  35631. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35632. }
  35633. else {
  35634. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35635. }
  35636. };
  35637. /**
  35638. * Specifies if material alpha testing should be turned on for the mesh
  35639. * @param mesh defines the mesh to check
  35640. */
  35641. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35642. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35643. };
  35644. /**
  35645. * Processes to execute after binding the material to a mesh
  35646. * @param mesh defines the rendered mesh
  35647. */
  35648. Material.prototype._afterBind = function (mesh) {
  35649. this._scene._cachedMaterial = this;
  35650. if (mesh) {
  35651. this._scene._cachedVisibility = mesh.visibility;
  35652. }
  35653. else {
  35654. this._scene._cachedVisibility = 1;
  35655. }
  35656. if (mesh) {
  35657. this.onBindObservable.notifyObservers(mesh);
  35658. }
  35659. if (this.disableDepthWrite) {
  35660. var engine = this._scene.getEngine();
  35661. this._cachedDepthWriteState = engine.getDepthWrite();
  35662. engine.setDepthWrite(false);
  35663. }
  35664. };
  35665. /**
  35666. * Unbinds the material from the mesh
  35667. */
  35668. Material.prototype.unbind = function () {
  35669. this.onUnBindObservable.notifyObservers(this);
  35670. if (this.disableDepthWrite) {
  35671. var engine = this._scene.getEngine();
  35672. engine.setDepthWrite(this._cachedDepthWriteState);
  35673. }
  35674. };
  35675. /**
  35676. * Gets the active textures from the material
  35677. * @returns an array of textures
  35678. */
  35679. Material.prototype.getActiveTextures = function () {
  35680. return [];
  35681. };
  35682. /**
  35683. * Specifies if the material uses a texture
  35684. * @param texture defines the texture to check against the material
  35685. * @returns a boolean specifying if the material uses the texture
  35686. */
  35687. Material.prototype.hasTexture = function (texture) {
  35688. return false;
  35689. };
  35690. /**
  35691. * Makes a duplicate of the material, and gives it a new name
  35692. * @param name defines the new name for the duplicated material
  35693. * @returns the cloned material
  35694. */
  35695. Material.prototype.clone = function (name) {
  35696. return null;
  35697. };
  35698. /**
  35699. * Gets the meshes bound to the material
  35700. * @returns an array of meshes bound to the material
  35701. */
  35702. Material.prototype.getBindedMeshes = function () {
  35703. var result = new Array();
  35704. for (var index = 0; index < this._scene.meshes.length; index++) {
  35705. var mesh = this._scene.meshes[index];
  35706. if (mesh.material === this) {
  35707. result.push(mesh);
  35708. }
  35709. }
  35710. return result;
  35711. };
  35712. /**
  35713. * Force shader compilation
  35714. * @param mesh defines the mesh associated with this material
  35715. * @param onCompiled defines a function to execute once the material is compiled
  35716. * @param options defines the options to configure the compilation
  35717. */
  35718. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35719. var _this = this;
  35720. var localOptions = __assign({ clipPlane: false }, options);
  35721. var subMesh = new BABYLON.BaseSubMesh();
  35722. var scene = this.getScene();
  35723. var checkReady = function () {
  35724. if (!_this._scene || !_this._scene.getEngine()) {
  35725. return;
  35726. }
  35727. if (subMesh._materialDefines) {
  35728. subMesh._materialDefines._renderId = -1;
  35729. }
  35730. var clipPlaneState = scene.clipPlane;
  35731. if (localOptions.clipPlane) {
  35732. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35733. }
  35734. if (_this.storeEffectOnSubMeshes) {
  35735. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35736. if (onCompiled) {
  35737. onCompiled(_this);
  35738. }
  35739. }
  35740. else {
  35741. setTimeout(checkReady, 16);
  35742. }
  35743. }
  35744. else {
  35745. if (_this.isReady(mesh)) {
  35746. if (onCompiled) {
  35747. onCompiled(_this);
  35748. }
  35749. }
  35750. else {
  35751. setTimeout(checkReady, 16);
  35752. }
  35753. }
  35754. if (localOptions.clipPlane) {
  35755. scene.clipPlane = clipPlaneState;
  35756. }
  35757. };
  35758. checkReady();
  35759. };
  35760. /**
  35761. * Force shader compilation
  35762. * @param mesh defines the mesh that will use this material
  35763. * @param options defines additional options for compiling the shaders
  35764. * @returns a promise that resolves when the compilation completes
  35765. */
  35766. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35767. var _this = this;
  35768. return new Promise(function (resolve) {
  35769. _this.forceCompilation(mesh, function () {
  35770. resolve();
  35771. }, options);
  35772. });
  35773. };
  35774. /**
  35775. * Marks a define in the material to indicate that it needs to be re-computed
  35776. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35777. */
  35778. Material.prototype.markAsDirty = function (flag) {
  35779. if (flag & Material.TextureDirtyFlag) {
  35780. this._markAllSubMeshesAsTexturesDirty();
  35781. }
  35782. if (flag & Material.LightDirtyFlag) {
  35783. this._markAllSubMeshesAsLightsDirty();
  35784. }
  35785. if (flag & Material.FresnelDirtyFlag) {
  35786. this._markAllSubMeshesAsFresnelDirty();
  35787. }
  35788. if (flag & Material.AttributesDirtyFlag) {
  35789. this._markAllSubMeshesAsAttributesDirty();
  35790. }
  35791. if (flag & Material.MiscDirtyFlag) {
  35792. this._markAllSubMeshesAsMiscDirty();
  35793. }
  35794. this.getScene().resetCachedMaterial();
  35795. };
  35796. /**
  35797. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35798. * @param func defines a function which checks material defines against the submeshes
  35799. */
  35800. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35801. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35802. var mesh = _a[_i];
  35803. if (!mesh.subMeshes) {
  35804. continue;
  35805. }
  35806. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35807. var subMesh = _c[_b];
  35808. if (subMesh.getMaterial() !== this) {
  35809. continue;
  35810. }
  35811. if (!subMesh._materialDefines) {
  35812. continue;
  35813. }
  35814. func(subMesh._materialDefines);
  35815. }
  35816. }
  35817. };
  35818. /**
  35819. * Indicates that image processing needs to be re-calculated for all submeshes
  35820. */
  35821. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35822. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35823. };
  35824. /**
  35825. * Indicates that textures need to be re-calculated for all submeshes
  35826. */
  35827. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35828. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35829. };
  35830. /**
  35831. * Indicates that fresnel needs to be re-calculated for all submeshes
  35832. */
  35833. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35834. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35835. };
  35836. /**
  35837. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35838. */
  35839. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35840. this._markAllSubMeshesAsDirty(function (defines) {
  35841. defines.markAsFresnelDirty();
  35842. defines.markAsMiscDirty();
  35843. });
  35844. };
  35845. /**
  35846. * Indicates that lights need to be re-calculated for all submeshes
  35847. */
  35848. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35849. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35850. };
  35851. /**
  35852. * Indicates that attributes need to be re-calculated for all submeshes
  35853. */
  35854. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35855. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35856. };
  35857. /**
  35858. * Indicates that misc needs to be re-calculated for all submeshes
  35859. */
  35860. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35861. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35862. };
  35863. /**
  35864. * Indicates that textures and misc need to be re-calculated for all submeshes
  35865. */
  35866. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35867. this._markAllSubMeshesAsDirty(function (defines) {
  35868. defines.markAsTexturesDirty();
  35869. defines.markAsMiscDirty();
  35870. });
  35871. };
  35872. /**
  35873. * Disposes the material
  35874. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35875. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35876. */
  35877. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35878. // Animations
  35879. this.getScene().stopAnimation(this);
  35880. this.getScene().freeProcessedMaterials();
  35881. // Remove from scene
  35882. var index = this._scene.materials.indexOf(this);
  35883. if (index >= 0) {
  35884. this._scene.materials.splice(index, 1);
  35885. }
  35886. // Remove from meshes
  35887. for (index = 0; index < this._scene.meshes.length; index++) {
  35888. var mesh = this._scene.meshes[index];
  35889. if (mesh.material === this) {
  35890. mesh.material = null;
  35891. if (mesh.geometry) {
  35892. var geometry = (mesh.geometry);
  35893. if (this.storeEffectOnSubMeshes) {
  35894. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35895. var subMesh = _a[_i];
  35896. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35897. if (forceDisposeEffect && subMesh._materialEffect) {
  35898. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35899. }
  35900. }
  35901. }
  35902. else {
  35903. geometry._releaseVertexArrayObject(this._effect);
  35904. }
  35905. }
  35906. }
  35907. }
  35908. this._uniformBuffer.dispose();
  35909. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35910. if (forceDisposeEffect && this._effect) {
  35911. if (!this.storeEffectOnSubMeshes) {
  35912. this._scene.getEngine()._releaseEffect(this._effect);
  35913. }
  35914. this._effect = null;
  35915. }
  35916. // Callback
  35917. this.onDisposeObservable.notifyObservers(this);
  35918. this.onDisposeObservable.clear();
  35919. this.onBindObservable.clear();
  35920. this.onUnBindObservable.clear();
  35921. };
  35922. /**
  35923. * Serializes this material
  35924. * @returns the serialized material object
  35925. */
  35926. Material.prototype.serialize = function () {
  35927. return BABYLON.SerializationHelper.Serialize(this);
  35928. };
  35929. /**
  35930. * Creates a MultiMaterial from parsed MultiMaterial data.
  35931. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35932. * @param scene defines the hosting scene
  35933. * @returns a new MultiMaterial
  35934. */
  35935. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35936. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35937. multiMaterial.id = parsedMultiMaterial.id;
  35938. if (BABYLON.Tags) {
  35939. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35940. }
  35941. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35942. var subMatId = parsedMultiMaterial.materials[matIndex];
  35943. if (subMatId) {
  35944. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35945. }
  35946. else {
  35947. multiMaterial.subMaterials.push(null);
  35948. }
  35949. }
  35950. return multiMaterial;
  35951. };
  35952. /**
  35953. * Creates a material from parsed material data
  35954. * @param parsedMaterial defines parsed material data
  35955. * @param scene defines the hosting scene
  35956. * @param rootUrl defines the root URL to use to load textures
  35957. * @returns a new material
  35958. */
  35959. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35960. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35961. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35962. }
  35963. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35964. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35965. if (!BABYLON.LegacyPBRMaterial) {
  35966. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35967. return;
  35968. }
  35969. }
  35970. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35971. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35972. };
  35973. // Triangle views
  35974. Material._TriangleFillMode = 0;
  35975. Material._WireFrameFillMode = 1;
  35976. Material._PointFillMode = 2;
  35977. // Draw modes
  35978. Material._PointListDrawMode = 3;
  35979. Material._LineListDrawMode = 4;
  35980. Material._LineLoopDrawMode = 5;
  35981. Material._LineStripDrawMode = 6;
  35982. Material._TriangleStripDrawMode = 7;
  35983. Material._TriangleFanDrawMode = 8;
  35984. /**
  35985. * Stores the clock-wise side orientation
  35986. */
  35987. Material._ClockWiseSideOrientation = 0;
  35988. /**
  35989. * Stores the counter clock-wise side orientation
  35990. */
  35991. Material._CounterClockWiseSideOrientation = 1;
  35992. /**
  35993. * The dirty texture flag value
  35994. */
  35995. Material._TextureDirtyFlag = 1;
  35996. /**
  35997. * The dirty light flag value
  35998. */
  35999. Material._LightDirtyFlag = 2;
  36000. /**
  36001. * The dirty fresnel flag value
  36002. */
  36003. Material._FresnelDirtyFlag = 4;
  36004. /**
  36005. * The dirty attribute flag value
  36006. */
  36007. Material._AttributesDirtyFlag = 8;
  36008. /**
  36009. * The dirty misc flag value
  36010. */
  36011. Material._MiscDirtyFlag = 16;
  36012. __decorate([
  36013. BABYLON.serialize()
  36014. ], Material.prototype, "id", void 0);
  36015. __decorate([
  36016. BABYLON.serialize()
  36017. ], Material.prototype, "uniqueId", void 0);
  36018. __decorate([
  36019. BABYLON.serialize()
  36020. ], Material.prototype, "name", void 0);
  36021. __decorate([
  36022. BABYLON.serialize()
  36023. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36024. __decorate([
  36025. BABYLON.serialize()
  36026. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36027. __decorate([
  36028. BABYLON.serialize()
  36029. ], Material.prototype, "state", void 0);
  36030. __decorate([
  36031. BABYLON.serialize("alpha")
  36032. ], Material.prototype, "_alpha", void 0);
  36033. __decorate([
  36034. BABYLON.serialize("backFaceCulling")
  36035. ], Material.prototype, "_backFaceCulling", void 0);
  36036. __decorate([
  36037. BABYLON.serialize()
  36038. ], Material.prototype, "sideOrientation", void 0);
  36039. __decorate([
  36040. BABYLON.serialize("alphaMode")
  36041. ], Material.prototype, "_alphaMode", void 0);
  36042. __decorate([
  36043. BABYLON.serialize()
  36044. ], Material.prototype, "_needDepthPrePass", void 0);
  36045. __decorate([
  36046. BABYLON.serialize()
  36047. ], Material.prototype, "disableDepthWrite", void 0);
  36048. __decorate([
  36049. BABYLON.serialize()
  36050. ], Material.prototype, "forceDepthWrite", void 0);
  36051. __decorate([
  36052. BABYLON.serialize()
  36053. ], Material.prototype, "separateCullingPass", void 0);
  36054. __decorate([
  36055. BABYLON.serialize("fogEnabled")
  36056. ], Material.prototype, "_fogEnabled", void 0);
  36057. __decorate([
  36058. BABYLON.serialize()
  36059. ], Material.prototype, "pointSize", void 0);
  36060. __decorate([
  36061. BABYLON.serialize()
  36062. ], Material.prototype, "zOffset", void 0);
  36063. __decorate([
  36064. BABYLON.serialize()
  36065. ], Material.prototype, "wireframe", null);
  36066. __decorate([
  36067. BABYLON.serialize()
  36068. ], Material.prototype, "pointsCloud", null);
  36069. __decorate([
  36070. BABYLON.serialize()
  36071. ], Material.prototype, "fillMode", null);
  36072. return Material;
  36073. }());
  36074. BABYLON.Material = Material;
  36075. })(BABYLON || (BABYLON = {}));
  36076. //# sourceMappingURL=babylon.material.js.map
  36077. var BABYLON;
  36078. (function (BABYLON) {
  36079. var UniformBuffer = /** @class */ (function () {
  36080. /**
  36081. * Uniform buffer objects.
  36082. *
  36083. * Handles blocks of uniform on the GPU.
  36084. *
  36085. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36086. *
  36087. * For more information, please refer to :
  36088. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36089. */
  36090. function UniformBuffer(engine, data, dynamic) {
  36091. this._engine = engine;
  36092. this._noUBO = !engine.supportsUniformBuffers;
  36093. this._dynamic = dynamic;
  36094. this._data = data || [];
  36095. this._uniformLocations = {};
  36096. this._uniformSizes = {};
  36097. this._uniformLocationPointer = 0;
  36098. this._needSync = false;
  36099. if (this._noUBO) {
  36100. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36101. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36102. this.updateFloat = this._updateFloatForEffect;
  36103. this.updateFloat2 = this._updateFloat2ForEffect;
  36104. this.updateFloat3 = this._updateFloat3ForEffect;
  36105. this.updateFloat4 = this._updateFloat4ForEffect;
  36106. this.updateMatrix = this._updateMatrixForEffect;
  36107. this.updateVector3 = this._updateVector3ForEffect;
  36108. this.updateVector4 = this._updateVector4ForEffect;
  36109. this.updateColor3 = this._updateColor3ForEffect;
  36110. this.updateColor4 = this._updateColor4ForEffect;
  36111. }
  36112. else {
  36113. this._engine._uniformBuffers.push(this);
  36114. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36115. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36116. this.updateFloat = this._updateFloatForUniform;
  36117. this.updateFloat2 = this._updateFloat2ForUniform;
  36118. this.updateFloat3 = this._updateFloat3ForUniform;
  36119. this.updateFloat4 = this._updateFloat4ForUniform;
  36120. this.updateMatrix = this._updateMatrixForUniform;
  36121. this.updateVector3 = this._updateVector3ForUniform;
  36122. this.updateVector4 = this._updateVector4ForUniform;
  36123. this.updateColor3 = this._updateColor3ForUniform;
  36124. this.updateColor4 = this._updateColor4ForUniform;
  36125. }
  36126. }
  36127. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36128. // Properties
  36129. /**
  36130. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36131. * or just falling back on setUniformXXX calls.
  36132. */
  36133. get: function () {
  36134. return !this._noUBO;
  36135. },
  36136. enumerable: true,
  36137. configurable: true
  36138. });
  36139. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36140. /**
  36141. * Indicates if the WebGL underlying uniform buffer is in sync
  36142. * with the javascript cache data.
  36143. */
  36144. get: function () {
  36145. return !this._needSync;
  36146. },
  36147. enumerable: true,
  36148. configurable: true
  36149. });
  36150. /**
  36151. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36152. * Also, a dynamic UniformBuffer will disable cache verification and always
  36153. * update the underlying WebGL uniform buffer to the GPU.
  36154. */
  36155. UniformBuffer.prototype.isDynamic = function () {
  36156. return this._dynamic !== undefined;
  36157. };
  36158. /**
  36159. * The data cache on JS side.
  36160. */
  36161. UniformBuffer.prototype.getData = function () {
  36162. return this._bufferData;
  36163. };
  36164. /**
  36165. * The underlying WebGL Uniform buffer.
  36166. */
  36167. UniformBuffer.prototype.getBuffer = function () {
  36168. return this._buffer;
  36169. };
  36170. /**
  36171. * std140 layout specifies how to align data within an UBO structure.
  36172. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36173. * for specs.
  36174. */
  36175. UniformBuffer.prototype._fillAlignment = function (size) {
  36176. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36177. // and 4x4 matrices
  36178. // TODO : change if other types are used
  36179. var alignment;
  36180. if (size <= 2) {
  36181. alignment = size;
  36182. }
  36183. else {
  36184. alignment = 4;
  36185. }
  36186. if ((this._uniformLocationPointer % alignment) !== 0) {
  36187. var oldPointer = this._uniformLocationPointer;
  36188. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36189. var diff = this._uniformLocationPointer - oldPointer;
  36190. for (var i = 0; i < diff; i++) {
  36191. this._data.push(0);
  36192. }
  36193. }
  36194. };
  36195. /**
  36196. * Adds an uniform in the buffer.
  36197. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36198. * for the layout to be correct !
  36199. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36200. * @param {number|number[]} size Data size, or data directly.
  36201. */
  36202. UniformBuffer.prototype.addUniform = function (name, size) {
  36203. if (this._noUBO) {
  36204. return;
  36205. }
  36206. if (this._uniformLocations[name] !== undefined) {
  36207. // Already existing uniform
  36208. return;
  36209. }
  36210. // This function must be called in the order of the shader layout !
  36211. // size can be the size of the uniform, or data directly
  36212. var data;
  36213. if (size instanceof Array) {
  36214. data = size;
  36215. size = data.length;
  36216. }
  36217. else {
  36218. size = size;
  36219. data = [];
  36220. // Fill with zeros
  36221. for (var i = 0; i < size; i++) {
  36222. data.push(0);
  36223. }
  36224. }
  36225. this._fillAlignment(size);
  36226. this._uniformSizes[name] = size;
  36227. this._uniformLocations[name] = this._uniformLocationPointer;
  36228. this._uniformLocationPointer += size;
  36229. for (var i = 0; i < size; i++) {
  36230. this._data.push(data[i]);
  36231. }
  36232. this._needSync = true;
  36233. };
  36234. /**
  36235. * Wrapper for addUniform.
  36236. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36237. * @param {Matrix} mat A 4x4 matrix.
  36238. */
  36239. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36240. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36241. };
  36242. /**
  36243. * Wrapper for addUniform.
  36244. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36245. * @param {number} x
  36246. * @param {number} y
  36247. */
  36248. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36249. var temp = [x, y];
  36250. this.addUniform(name, temp);
  36251. };
  36252. /**
  36253. * Wrapper for addUniform.
  36254. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36255. * @param {number} x
  36256. * @param {number} y
  36257. * @param {number} z
  36258. */
  36259. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36260. var temp = [x, y, z];
  36261. this.addUniform(name, temp);
  36262. };
  36263. /**
  36264. * Wrapper for addUniform.
  36265. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36266. * @param {Color3} color
  36267. */
  36268. UniformBuffer.prototype.addColor3 = function (name, color) {
  36269. var temp = new Array();
  36270. color.toArray(temp);
  36271. this.addUniform(name, temp);
  36272. };
  36273. /**
  36274. * Wrapper for addUniform.
  36275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36276. * @param {Color3} color
  36277. * @param {number} alpha
  36278. */
  36279. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36280. var temp = new Array();
  36281. color.toArray(temp);
  36282. temp.push(alpha);
  36283. this.addUniform(name, temp);
  36284. };
  36285. /**
  36286. * Wrapper for addUniform.
  36287. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36288. * @param {Vector3} vector
  36289. */
  36290. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36291. var temp = new Array();
  36292. vector.toArray(temp);
  36293. this.addUniform(name, temp);
  36294. };
  36295. /**
  36296. * Wrapper for addUniform.
  36297. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36298. */
  36299. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36300. this.addUniform(name, 12);
  36301. };
  36302. /**
  36303. * Wrapper for addUniform.
  36304. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36305. */
  36306. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36307. this.addUniform(name, 8);
  36308. };
  36309. /**
  36310. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36311. */
  36312. UniformBuffer.prototype.create = function () {
  36313. if (this._noUBO) {
  36314. return;
  36315. }
  36316. if (this._buffer) {
  36317. return; // nothing to do
  36318. }
  36319. // See spec, alignment must be filled as a vec4
  36320. this._fillAlignment(4);
  36321. this._bufferData = new Float32Array(this._data);
  36322. this._rebuild();
  36323. this._needSync = true;
  36324. };
  36325. UniformBuffer.prototype._rebuild = function () {
  36326. if (this._noUBO) {
  36327. return;
  36328. }
  36329. if (this._dynamic) {
  36330. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36331. }
  36332. else {
  36333. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36334. }
  36335. };
  36336. /**
  36337. * Updates the WebGL Uniform Buffer on the GPU.
  36338. * If the `dynamic` flag is set to true, no cache comparison is done.
  36339. * Otherwise, the buffer will be updated only if the cache differs.
  36340. */
  36341. UniformBuffer.prototype.update = function () {
  36342. if (!this._buffer) {
  36343. this.create();
  36344. return;
  36345. }
  36346. if (!this._dynamic && !this._needSync) {
  36347. return;
  36348. }
  36349. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36350. this._needSync = false;
  36351. };
  36352. /**
  36353. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36354. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36355. * @param {number[]|Float32Array} data Flattened data
  36356. * @param {number} size Size of the data.
  36357. */
  36358. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36359. var location = this._uniformLocations[uniformName];
  36360. if (location === undefined) {
  36361. if (this._buffer) {
  36362. // Cannot add an uniform if the buffer is already created
  36363. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36364. return;
  36365. }
  36366. this.addUniform(uniformName, size);
  36367. location = this._uniformLocations[uniformName];
  36368. }
  36369. if (!this._buffer) {
  36370. this.create();
  36371. }
  36372. if (!this._dynamic) {
  36373. // Cache for static uniform buffers
  36374. var changed = false;
  36375. for (var i = 0; i < size; i++) {
  36376. if (this._bufferData[location + i] !== data[i]) {
  36377. changed = true;
  36378. this._bufferData[location + i] = data[i];
  36379. }
  36380. }
  36381. this._needSync = this._needSync || changed;
  36382. }
  36383. else {
  36384. // No cache for dynamic
  36385. for (var i = 0; i < size; i++) {
  36386. this._bufferData[location + i] = data[i];
  36387. }
  36388. }
  36389. };
  36390. // Update methods
  36391. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36392. // To match std140, matrix must be realigned
  36393. for (var i = 0; i < 3; i++) {
  36394. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36395. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36396. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36397. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36398. }
  36399. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36400. };
  36401. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36402. this._currentEffect.setMatrix3x3(name, matrix);
  36403. };
  36404. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36405. this._currentEffect.setMatrix2x2(name, matrix);
  36406. };
  36407. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36408. // To match std140, matrix must be realigned
  36409. for (var i = 0; i < 2; i++) {
  36410. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36411. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36412. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36413. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36414. }
  36415. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36416. };
  36417. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36418. this._currentEffect.setFloat(name, x);
  36419. };
  36420. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36421. UniformBuffer._tempBuffer[0] = x;
  36422. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36423. };
  36424. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36425. if (suffix === void 0) { suffix = ""; }
  36426. this._currentEffect.setFloat2(name + suffix, x, y);
  36427. };
  36428. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36429. if (suffix === void 0) { suffix = ""; }
  36430. UniformBuffer._tempBuffer[0] = x;
  36431. UniformBuffer._tempBuffer[1] = y;
  36432. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36433. };
  36434. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36435. if (suffix === void 0) { suffix = ""; }
  36436. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36437. };
  36438. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36439. if (suffix === void 0) { suffix = ""; }
  36440. UniformBuffer._tempBuffer[0] = x;
  36441. UniformBuffer._tempBuffer[1] = y;
  36442. UniformBuffer._tempBuffer[2] = z;
  36443. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36444. };
  36445. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36446. if (suffix === void 0) { suffix = ""; }
  36447. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36448. };
  36449. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36450. if (suffix === void 0) { suffix = ""; }
  36451. UniformBuffer._tempBuffer[0] = x;
  36452. UniformBuffer._tempBuffer[1] = y;
  36453. UniformBuffer._tempBuffer[2] = z;
  36454. UniformBuffer._tempBuffer[3] = w;
  36455. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36456. };
  36457. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36458. this._currentEffect.setMatrix(name, mat);
  36459. };
  36460. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36461. this.updateUniform(name, mat.toArray(), 16);
  36462. };
  36463. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36464. this._currentEffect.setVector3(name, vector);
  36465. };
  36466. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36467. vector.toArray(UniformBuffer._tempBuffer);
  36468. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36469. };
  36470. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36471. this._currentEffect.setVector4(name, vector);
  36472. };
  36473. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36474. vector.toArray(UniformBuffer._tempBuffer);
  36475. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36476. };
  36477. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36478. if (suffix === void 0) { suffix = ""; }
  36479. this._currentEffect.setColor3(name + suffix, color);
  36480. };
  36481. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36482. if (suffix === void 0) { suffix = ""; }
  36483. color.toArray(UniformBuffer._tempBuffer);
  36484. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36485. };
  36486. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36487. if (suffix === void 0) { suffix = ""; }
  36488. this._currentEffect.setColor4(name + suffix, color, alpha);
  36489. };
  36490. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36491. if (suffix === void 0) { suffix = ""; }
  36492. color.toArray(UniformBuffer._tempBuffer);
  36493. UniformBuffer._tempBuffer[3] = alpha;
  36494. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36495. };
  36496. /**
  36497. * Sets a sampler uniform on the effect.
  36498. * @param {string} name Name of the sampler.
  36499. * @param {Texture} texture
  36500. */
  36501. UniformBuffer.prototype.setTexture = function (name, texture) {
  36502. this._currentEffect.setTexture(name, texture);
  36503. };
  36504. /**
  36505. * Directly updates the value of the uniform in the cache AND on the GPU.
  36506. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36507. * @param {number[]|Float32Array} data Flattened data
  36508. */
  36509. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36510. this.updateUniform(uniformName, data, data.length);
  36511. this.update();
  36512. };
  36513. /**
  36514. * Binds this uniform buffer to an effect.
  36515. * @param {Effect} effect
  36516. * @param {string} name Name of the uniform block in the shader.
  36517. */
  36518. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36519. this._currentEffect = effect;
  36520. if (this._noUBO || !this._buffer) {
  36521. return;
  36522. }
  36523. effect.bindUniformBuffer(this._buffer, name);
  36524. };
  36525. /**
  36526. * Disposes the uniform buffer.
  36527. */
  36528. UniformBuffer.prototype.dispose = function () {
  36529. if (this._noUBO) {
  36530. return;
  36531. }
  36532. var index = this._engine._uniformBuffers.indexOf(this);
  36533. if (index !== -1) {
  36534. this._engine._uniformBuffers.splice(index, 1);
  36535. }
  36536. if (!this._buffer) {
  36537. return;
  36538. }
  36539. if (this._engine._releaseBuffer(this._buffer)) {
  36540. this._buffer = null;
  36541. }
  36542. };
  36543. // Pool for avoiding memory leaks
  36544. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36545. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36546. return UniformBuffer;
  36547. }());
  36548. BABYLON.UniformBuffer = UniformBuffer;
  36549. })(BABYLON || (BABYLON = {}));
  36550. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36551. var BABYLON;
  36552. (function (BABYLON) {
  36553. /**
  36554. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36555. */
  36556. var VertexData = /** @class */ (function () {
  36557. function VertexData() {
  36558. }
  36559. /**
  36560. * Uses the passed data array to set the set the values for the specified kind of data
  36561. * @param data a linear array of floating numbers
  36562. * @param kind the type of data that is being set, eg positions, colors etc
  36563. */
  36564. VertexData.prototype.set = function (data, kind) {
  36565. switch (kind) {
  36566. case BABYLON.VertexBuffer.PositionKind:
  36567. this.positions = data;
  36568. break;
  36569. case BABYLON.VertexBuffer.NormalKind:
  36570. this.normals = data;
  36571. break;
  36572. case BABYLON.VertexBuffer.TangentKind:
  36573. this.tangents = data;
  36574. break;
  36575. case BABYLON.VertexBuffer.UVKind:
  36576. this.uvs = data;
  36577. break;
  36578. case BABYLON.VertexBuffer.UV2Kind:
  36579. this.uvs2 = data;
  36580. break;
  36581. case BABYLON.VertexBuffer.UV3Kind:
  36582. this.uvs3 = data;
  36583. break;
  36584. case BABYLON.VertexBuffer.UV4Kind:
  36585. this.uvs4 = data;
  36586. break;
  36587. case BABYLON.VertexBuffer.UV5Kind:
  36588. this.uvs5 = data;
  36589. break;
  36590. case BABYLON.VertexBuffer.UV6Kind:
  36591. this.uvs6 = data;
  36592. break;
  36593. case BABYLON.VertexBuffer.ColorKind:
  36594. this.colors = data;
  36595. break;
  36596. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36597. this.matricesIndices = data;
  36598. break;
  36599. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36600. this.matricesWeights = data;
  36601. break;
  36602. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36603. this.matricesIndicesExtra = data;
  36604. break;
  36605. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36606. this.matricesWeightsExtra = data;
  36607. break;
  36608. }
  36609. };
  36610. /**
  36611. * Associates the vertexData to the passed Mesh.
  36612. * Sets it as updatable or not (default `false`)
  36613. * @param mesh the mesh the vertexData is applied to
  36614. * @param updatable when used and having the value true allows new data to update the vertexData
  36615. * @returns the VertexData
  36616. */
  36617. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36618. this._applyTo(mesh, updatable);
  36619. return this;
  36620. };
  36621. /**
  36622. * Associates the vertexData to the passed Geometry.
  36623. * Sets it as updatable or not (default `false`)
  36624. * @param geometry the geometry the vertexData is applied to
  36625. * @param updatable when used and having the value true allows new data to update the vertexData
  36626. * @returns VertexData
  36627. */
  36628. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36629. this._applyTo(geometry, updatable);
  36630. return this;
  36631. };
  36632. /**
  36633. * Updates the associated mesh
  36634. * @param mesh the mesh to be updated
  36635. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36636. * @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
  36637. * @returns VertexData
  36638. */
  36639. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36640. this._update(mesh);
  36641. return this;
  36642. };
  36643. /**
  36644. * Updates the associated geometry
  36645. * @param geometry the geometry to be updated
  36646. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36647. * @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
  36648. * @returns VertexData.
  36649. */
  36650. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36651. this._update(geometry);
  36652. return this;
  36653. };
  36654. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36655. if (updatable === void 0) { updatable = false; }
  36656. if (this.positions) {
  36657. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36658. }
  36659. if (this.normals) {
  36660. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36661. }
  36662. if (this.tangents) {
  36663. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36664. }
  36665. if (this.uvs) {
  36666. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36667. }
  36668. if (this.uvs2) {
  36669. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36670. }
  36671. if (this.uvs3) {
  36672. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36673. }
  36674. if (this.uvs4) {
  36675. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36676. }
  36677. if (this.uvs5) {
  36678. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36679. }
  36680. if (this.uvs6) {
  36681. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36682. }
  36683. if (this.colors) {
  36684. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36685. }
  36686. if (this.matricesIndices) {
  36687. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36688. }
  36689. if (this.matricesWeights) {
  36690. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36691. }
  36692. if (this.matricesIndicesExtra) {
  36693. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36694. }
  36695. if (this.matricesWeightsExtra) {
  36696. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36697. }
  36698. if (this.indices) {
  36699. meshOrGeometry.setIndices(this.indices, null, updatable);
  36700. }
  36701. else {
  36702. meshOrGeometry.setIndices([], null);
  36703. }
  36704. return this;
  36705. };
  36706. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36707. if (this.positions) {
  36708. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36709. }
  36710. if (this.normals) {
  36711. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36712. }
  36713. if (this.tangents) {
  36714. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36715. }
  36716. if (this.uvs) {
  36717. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36718. }
  36719. if (this.uvs2) {
  36720. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36721. }
  36722. if (this.uvs3) {
  36723. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36724. }
  36725. if (this.uvs4) {
  36726. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36727. }
  36728. if (this.uvs5) {
  36729. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36730. }
  36731. if (this.uvs6) {
  36732. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36733. }
  36734. if (this.colors) {
  36735. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36736. }
  36737. if (this.matricesIndices) {
  36738. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36739. }
  36740. if (this.matricesWeights) {
  36741. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36742. }
  36743. if (this.matricesIndicesExtra) {
  36744. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36745. }
  36746. if (this.matricesWeightsExtra) {
  36747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36748. }
  36749. if (this.indices) {
  36750. meshOrGeometry.setIndices(this.indices, null);
  36751. }
  36752. return this;
  36753. };
  36754. /**
  36755. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36756. * @param matrix the transforming matrix
  36757. * @returns the VertexData
  36758. */
  36759. VertexData.prototype.transform = function (matrix) {
  36760. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36761. var transformed = BABYLON.Vector3.Zero();
  36762. var index;
  36763. if (this.positions) {
  36764. var position = BABYLON.Vector3.Zero();
  36765. for (index = 0; index < this.positions.length; index += 3) {
  36766. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36767. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36768. this.positions[index] = transformed.x;
  36769. this.positions[index + 1] = transformed.y;
  36770. this.positions[index + 2] = transformed.z;
  36771. }
  36772. }
  36773. if (this.normals) {
  36774. var normal = BABYLON.Vector3.Zero();
  36775. for (index = 0; index < this.normals.length; index += 3) {
  36776. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36777. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36778. this.normals[index] = transformed.x;
  36779. this.normals[index + 1] = transformed.y;
  36780. this.normals[index + 2] = transformed.z;
  36781. }
  36782. }
  36783. if (this.tangents) {
  36784. var tangent = BABYLON.Vector4.Zero();
  36785. var tangentTransformed = BABYLON.Vector4.Zero();
  36786. for (index = 0; index < this.tangents.length; index += 4) {
  36787. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36788. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36789. this.tangents[index] = tangentTransformed.x;
  36790. this.tangents[index + 1] = tangentTransformed.y;
  36791. this.tangents[index + 2] = tangentTransformed.z;
  36792. this.tangents[index + 3] = tangentTransformed.w;
  36793. }
  36794. }
  36795. if (flip && this.indices) {
  36796. for (index = 0; index < this.indices.length; index += 3) {
  36797. var tmp = this.indices[index + 1];
  36798. this.indices[index + 1] = this.indices[index + 2];
  36799. this.indices[index + 2] = tmp;
  36800. }
  36801. }
  36802. return this;
  36803. };
  36804. /**
  36805. * Merges the passed VertexData into the current one
  36806. * @param other the VertexData to be merged into the current one
  36807. * @returns the modified VertexData
  36808. */
  36809. VertexData.prototype.merge = function (other) {
  36810. this._validate();
  36811. other._validate();
  36812. if (!this.normals !== !other.normals ||
  36813. !this.tangents !== !other.tangents ||
  36814. !this.uvs !== !other.uvs ||
  36815. !this.uvs2 !== !other.uvs2 ||
  36816. !this.uvs3 !== !other.uvs3 ||
  36817. !this.uvs4 !== !other.uvs4 ||
  36818. !this.uvs5 !== !other.uvs5 ||
  36819. !this.uvs6 !== !other.uvs6 ||
  36820. !this.colors !== !other.colors ||
  36821. !this.matricesIndices !== !other.matricesIndices ||
  36822. !this.matricesWeights !== !other.matricesWeights ||
  36823. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36824. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36825. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36826. }
  36827. if (other.indices) {
  36828. if (!this.indices) {
  36829. this.indices = [];
  36830. }
  36831. var offset = this.positions ? this.positions.length / 3 : 0;
  36832. for (var index = 0; index < other.indices.length; index++) {
  36833. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36834. this.indices.push(other.indices[index] + offset);
  36835. }
  36836. }
  36837. this.positions = this._mergeElement(this.positions, other.positions);
  36838. this.normals = this._mergeElement(this.normals, other.normals);
  36839. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36840. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36841. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36842. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36843. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36844. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36845. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36846. this.colors = this._mergeElement(this.colors, other.colors);
  36847. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36848. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36849. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36850. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36851. return this;
  36852. };
  36853. VertexData.prototype._mergeElement = function (source, other) {
  36854. if (!source) {
  36855. return other;
  36856. }
  36857. if (!other) {
  36858. return source;
  36859. }
  36860. var len = other.length + source.length;
  36861. var isSrcTypedArray = source instanceof Float32Array;
  36862. var isOthTypedArray = other instanceof Float32Array;
  36863. // use non-loop method when the source is Float32Array
  36864. if (isSrcTypedArray) {
  36865. var ret32 = new Float32Array(len);
  36866. ret32.set(source);
  36867. ret32.set(other, source.length);
  36868. return ret32;
  36869. // source is number[], when other is also use concat
  36870. }
  36871. else if (!isOthTypedArray) {
  36872. return source.concat(other);
  36873. // source is a number[], but other is a Float32Array, loop required
  36874. }
  36875. else {
  36876. var ret = source.slice(0); // copy source to a separate array
  36877. for (var i = 0, len = other.length; i < len; i++) {
  36878. ret.push(other[i]);
  36879. }
  36880. return ret;
  36881. }
  36882. };
  36883. VertexData.prototype._validate = function () {
  36884. if (!this.positions) {
  36885. throw new Error("Positions are required");
  36886. }
  36887. var getElementCount = function (kind, values) {
  36888. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36889. if ((values.length % stride) !== 0) {
  36890. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36891. }
  36892. return values.length / stride;
  36893. };
  36894. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36895. var validateElementCount = function (kind, values) {
  36896. var elementCount = getElementCount(kind, values);
  36897. if (elementCount !== positionsElementCount) {
  36898. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36899. }
  36900. };
  36901. if (this.normals)
  36902. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36903. if (this.tangents)
  36904. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36905. if (this.uvs)
  36906. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36907. if (this.uvs2)
  36908. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36909. if (this.uvs3)
  36910. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36911. if (this.uvs4)
  36912. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36913. if (this.uvs5)
  36914. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36915. if (this.uvs6)
  36916. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36917. if (this.colors)
  36918. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36919. if (this.matricesIndices)
  36920. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36921. if (this.matricesWeights)
  36922. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36923. if (this.matricesIndicesExtra)
  36924. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36925. if (this.matricesWeightsExtra)
  36926. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36927. };
  36928. /**
  36929. * Serializes the VertexData
  36930. * @returns a serialized object
  36931. */
  36932. VertexData.prototype.serialize = function () {
  36933. var serializationObject = this.serialize();
  36934. if (this.positions) {
  36935. serializationObject.positions = this.positions;
  36936. }
  36937. if (this.normals) {
  36938. serializationObject.normals = this.normals;
  36939. }
  36940. if (this.tangents) {
  36941. serializationObject.tangents = this.tangents;
  36942. }
  36943. if (this.uvs) {
  36944. serializationObject.uvs = this.uvs;
  36945. }
  36946. if (this.uvs2) {
  36947. serializationObject.uvs2 = this.uvs2;
  36948. }
  36949. if (this.uvs3) {
  36950. serializationObject.uvs3 = this.uvs3;
  36951. }
  36952. if (this.uvs4) {
  36953. serializationObject.uvs4 = this.uvs4;
  36954. }
  36955. if (this.uvs5) {
  36956. serializationObject.uvs5 = this.uvs5;
  36957. }
  36958. if (this.uvs6) {
  36959. serializationObject.uvs6 = this.uvs6;
  36960. }
  36961. if (this.colors) {
  36962. serializationObject.colors = this.colors;
  36963. }
  36964. if (this.matricesIndices) {
  36965. serializationObject.matricesIndices = this.matricesIndices;
  36966. serializationObject.matricesIndices._isExpanded = true;
  36967. }
  36968. if (this.matricesWeights) {
  36969. serializationObject.matricesWeights = this.matricesWeights;
  36970. }
  36971. if (this.matricesIndicesExtra) {
  36972. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36973. serializationObject.matricesIndicesExtra._isExpanded = true;
  36974. }
  36975. if (this.matricesWeightsExtra) {
  36976. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36977. }
  36978. serializationObject.indices = this.indices;
  36979. return serializationObject;
  36980. };
  36981. // Statics
  36982. /**
  36983. * Extracts the vertexData from a mesh
  36984. * @param mesh the mesh from which to extract the VertexData
  36985. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36986. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36987. * @returns the object VertexData associated to the passed mesh
  36988. */
  36989. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36990. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36991. };
  36992. /**
  36993. * Extracts the vertexData from the geometry
  36994. * @param geometry the geometry from which to extract the VertexData
  36995. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36996. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36997. * @returns the object VertexData associated to the passed mesh
  36998. */
  36999. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37000. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37001. };
  37002. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37003. var result = new VertexData();
  37004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37005. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37006. }
  37007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37008. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37009. }
  37010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37011. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37012. }
  37013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37014. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37015. }
  37016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37017. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37018. }
  37019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37020. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37021. }
  37022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37023. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37024. }
  37025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37026. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37027. }
  37028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37029. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37030. }
  37031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37032. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37033. }
  37034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37035. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37036. }
  37037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37038. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37039. }
  37040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37041. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37042. }
  37043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37044. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37045. }
  37046. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37047. return result;
  37048. };
  37049. /**
  37050. * Creates the VertexData for a Ribbon
  37051. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37052. * * pathArray array of paths, each of which an array of successive Vector3
  37053. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37054. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37055. * * 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
  37056. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37057. * * 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)
  37058. * * 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)
  37059. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37060. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37061. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37062. * @returns the VertexData of the ribbon
  37063. */
  37064. VertexData.CreateRibbon = function (options) {
  37065. var pathArray = options.pathArray;
  37066. var closeArray = options.closeArray || false;
  37067. var closePath = options.closePath || false;
  37068. var invertUV = options.invertUV || false;
  37069. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37070. var offset = options.offset || defaultOffset;
  37071. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37072. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37073. var customUV = options.uvs;
  37074. var customColors = options.colors;
  37075. var positions = [];
  37076. var indices = [];
  37077. var normals = [];
  37078. var uvs = [];
  37079. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37080. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37081. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37082. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37083. var minlg; // minimal length among all paths from pathArray
  37084. var lg = []; // array of path lengths : nb of vertex per path
  37085. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37086. var p; // path iterator
  37087. var i; // point iterator
  37088. var j; // point iterator
  37089. // if single path in pathArray
  37090. if (pathArray.length < 2) {
  37091. var ar1 = [];
  37092. var ar2 = [];
  37093. for (i = 0; i < pathArray[0].length - offset; i++) {
  37094. ar1.push(pathArray[0][i]);
  37095. ar2.push(pathArray[0][i + offset]);
  37096. }
  37097. pathArray = [ar1, ar2];
  37098. }
  37099. // positions and horizontal distances (u)
  37100. var idc = 0;
  37101. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37102. var path;
  37103. var l;
  37104. minlg = pathArray[0].length;
  37105. var vectlg;
  37106. var dist;
  37107. for (p = 0; p < pathArray.length; p++) {
  37108. uTotalDistance[p] = 0;
  37109. us[p] = [0];
  37110. path = pathArray[p];
  37111. l = path.length;
  37112. minlg = (minlg < l) ? minlg : l;
  37113. j = 0;
  37114. while (j < l) {
  37115. positions.push(path[j].x, path[j].y, path[j].z);
  37116. if (j > 0) {
  37117. vectlg = path[j].subtract(path[j - 1]).length();
  37118. dist = vectlg + uTotalDistance[p];
  37119. us[p].push(dist);
  37120. uTotalDistance[p] = dist;
  37121. }
  37122. j++;
  37123. }
  37124. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37125. j--;
  37126. positions.push(path[0].x, path[0].y, path[0].z);
  37127. vectlg = path[j].subtract(path[0]).length();
  37128. dist = vectlg + uTotalDistance[p];
  37129. us[p].push(dist);
  37130. uTotalDistance[p] = dist;
  37131. }
  37132. lg[p] = l + closePathCorr;
  37133. idx[p] = idc;
  37134. idc += (l + closePathCorr);
  37135. }
  37136. // vertical distances (v)
  37137. var path1;
  37138. var path2;
  37139. var vertex1 = null;
  37140. var vertex2 = null;
  37141. for (i = 0; i < minlg + closePathCorr; i++) {
  37142. vTotalDistance[i] = 0;
  37143. vs[i] = [0];
  37144. for (p = 0; p < pathArray.length - 1; p++) {
  37145. path1 = pathArray[p];
  37146. path2 = pathArray[p + 1];
  37147. if (i === minlg) { // closePath
  37148. vertex1 = path1[0];
  37149. vertex2 = path2[0];
  37150. }
  37151. else {
  37152. vertex1 = path1[i];
  37153. vertex2 = path2[i];
  37154. }
  37155. vectlg = vertex2.subtract(vertex1).length();
  37156. dist = vectlg + vTotalDistance[i];
  37157. vs[i].push(dist);
  37158. vTotalDistance[i] = dist;
  37159. }
  37160. if (closeArray && vertex2 && vertex1) {
  37161. path1 = pathArray[p];
  37162. path2 = pathArray[0];
  37163. if (i === minlg) { // closePath
  37164. vertex2 = path2[0];
  37165. }
  37166. vectlg = vertex2.subtract(vertex1).length();
  37167. dist = vectlg + vTotalDistance[i];
  37168. vTotalDistance[i] = dist;
  37169. }
  37170. }
  37171. // uvs
  37172. var u;
  37173. var v;
  37174. if (customUV) {
  37175. for (p = 0; p < customUV.length; p++) {
  37176. uvs.push(customUV[p].x, customUV[p].y);
  37177. }
  37178. }
  37179. else {
  37180. for (p = 0; p < pathArray.length; p++) {
  37181. for (i = 0; i < minlg + closePathCorr; i++) {
  37182. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37183. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37184. if (invertUV) {
  37185. uvs.push(v, u);
  37186. }
  37187. else {
  37188. uvs.push(u, v);
  37189. }
  37190. }
  37191. }
  37192. }
  37193. // indices
  37194. p = 0; // path index
  37195. var pi = 0; // positions array index
  37196. var l1 = lg[p] - 1; // path1 length
  37197. var l2 = lg[p + 1] - 1; // path2 length
  37198. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37199. var shft = idx[1] - idx[0]; // shift
  37200. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37201. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37202. // 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
  37203. indices.push(pi, pi + shft, pi + 1);
  37204. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37205. pi += 1;
  37206. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37207. p++;
  37208. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37209. shft = idx[0] - idx[p];
  37210. l1 = lg[p] - 1;
  37211. l2 = lg[0] - 1;
  37212. }
  37213. else {
  37214. shft = idx[p + 1] - idx[p];
  37215. l1 = lg[p] - 1;
  37216. l2 = lg[p + 1] - 1;
  37217. }
  37218. pi = idx[p];
  37219. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37220. }
  37221. }
  37222. // normals
  37223. VertexData.ComputeNormals(positions, indices, normals);
  37224. if (closePath) { // update both the first and last vertex normals to their average value
  37225. var indexFirst = 0;
  37226. var indexLast = 0;
  37227. for (p = 0; p < pathArray.length; p++) {
  37228. indexFirst = idx[p] * 3;
  37229. if (p + 1 < pathArray.length) {
  37230. indexLast = (idx[p + 1] - 1) * 3;
  37231. }
  37232. else {
  37233. indexLast = normals.length - 3;
  37234. }
  37235. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37236. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37237. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37238. normals[indexLast] = normals[indexFirst];
  37239. normals[indexLast + 1] = normals[indexFirst + 1];
  37240. normals[indexLast + 2] = normals[indexFirst + 2];
  37241. }
  37242. }
  37243. // sides
  37244. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37245. // Colors
  37246. var colors = null;
  37247. if (customColors) {
  37248. colors = new Float32Array(customColors.length * 4);
  37249. for (var c = 0; c < customColors.length; c++) {
  37250. colors[c * 4] = customColors[c].r;
  37251. colors[c * 4 + 1] = customColors[c].g;
  37252. colors[c * 4 + 2] = customColors[c].b;
  37253. colors[c * 4 + 3] = customColors[c].a;
  37254. }
  37255. }
  37256. // Result
  37257. var vertexData = new VertexData();
  37258. var positions32 = new Float32Array(positions);
  37259. var normals32 = new Float32Array(normals);
  37260. var uvs32 = new Float32Array(uvs);
  37261. vertexData.indices = indices;
  37262. vertexData.positions = positions32;
  37263. vertexData.normals = normals32;
  37264. vertexData.uvs = uvs32;
  37265. if (colors) {
  37266. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37267. }
  37268. if (closePath) {
  37269. vertexData._idx = idx;
  37270. }
  37271. return vertexData;
  37272. };
  37273. /**
  37274. * Creates the VertexData for a box
  37275. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37276. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37277. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37278. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37279. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37280. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37281. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37282. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37283. * * 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)
  37284. * * 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)
  37285. * @returns the VertexData of the box
  37286. */
  37287. VertexData.CreateBox = function (options) {
  37288. var normalsSource = [
  37289. new BABYLON.Vector3(0, 0, 1),
  37290. new BABYLON.Vector3(0, 0, -1),
  37291. new BABYLON.Vector3(1, 0, 0),
  37292. new BABYLON.Vector3(-1, 0, 0),
  37293. new BABYLON.Vector3(0, 1, 0),
  37294. new BABYLON.Vector3(0, -1, 0)
  37295. ];
  37296. var indices = [];
  37297. var positions = [];
  37298. var normals = [];
  37299. var uvs = [];
  37300. var width = options.width || options.size || 1;
  37301. var height = options.height || options.size || 1;
  37302. var depth = options.depth || options.size || 1;
  37303. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37304. var faceUV = options.faceUV || new Array(6);
  37305. var faceColors = options.faceColors;
  37306. var colors = [];
  37307. // default face colors and UV if undefined
  37308. for (var f = 0; f < 6; f++) {
  37309. if (faceUV[f] === undefined) {
  37310. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37311. }
  37312. if (faceColors && faceColors[f] === undefined) {
  37313. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37314. }
  37315. }
  37316. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37317. // Create each face in turn.
  37318. for (var index = 0; index < normalsSource.length; index++) {
  37319. var normal = normalsSource[index];
  37320. // Get two vectors perpendicular to the face normal and to each other.
  37321. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37322. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37323. // Six indices (two triangles) per face.
  37324. var verticesLength = positions.length / 3;
  37325. indices.push(verticesLength);
  37326. indices.push(verticesLength + 1);
  37327. indices.push(verticesLength + 2);
  37328. indices.push(verticesLength);
  37329. indices.push(verticesLength + 2);
  37330. indices.push(verticesLength + 3);
  37331. // Four vertices per face.
  37332. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37333. positions.push(vertex.x, vertex.y, vertex.z);
  37334. normals.push(normal.x, normal.y, normal.z);
  37335. uvs.push(faceUV[index].z, faceUV[index].w);
  37336. if (faceColors) {
  37337. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37338. }
  37339. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37340. positions.push(vertex.x, vertex.y, vertex.z);
  37341. normals.push(normal.x, normal.y, normal.z);
  37342. uvs.push(faceUV[index].x, faceUV[index].w);
  37343. if (faceColors) {
  37344. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37345. }
  37346. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37347. positions.push(vertex.x, vertex.y, vertex.z);
  37348. normals.push(normal.x, normal.y, normal.z);
  37349. uvs.push(faceUV[index].x, faceUV[index].y);
  37350. if (faceColors) {
  37351. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37352. }
  37353. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37354. positions.push(vertex.x, vertex.y, vertex.z);
  37355. normals.push(normal.x, normal.y, normal.z);
  37356. uvs.push(faceUV[index].z, faceUV[index].y);
  37357. if (faceColors) {
  37358. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37359. }
  37360. }
  37361. // sides
  37362. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37363. // Result
  37364. var vertexData = new VertexData();
  37365. vertexData.indices = indices;
  37366. vertexData.positions = positions;
  37367. vertexData.normals = normals;
  37368. vertexData.uvs = uvs;
  37369. if (faceColors) {
  37370. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37371. vertexData.colors = totalColors;
  37372. }
  37373. return vertexData;
  37374. };
  37375. /**
  37376. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37377. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37378. * * segments sets the number of horizontal strips optional, default 32
  37379. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37380. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37381. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37382. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37383. * * 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
  37384. * * 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
  37385. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37386. * * 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)
  37387. * * 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)
  37388. * @returns the VertexData of the ellipsoid
  37389. */
  37390. VertexData.CreateSphere = function (options) {
  37391. var segments = options.segments || 32;
  37392. var diameterX = options.diameterX || options.diameter || 1;
  37393. var diameterY = options.diameterY || options.diameter || 1;
  37394. var diameterZ = options.diameterZ || options.diameter || 1;
  37395. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37396. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37397. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37398. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37399. var totalZRotationSteps = 2 + segments;
  37400. var totalYRotationSteps = 2 * totalZRotationSteps;
  37401. var indices = [];
  37402. var positions = [];
  37403. var normals = [];
  37404. var uvs = [];
  37405. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37406. var normalizedZ = zRotationStep / totalZRotationSteps;
  37407. var angleZ = normalizedZ * Math.PI * slice;
  37408. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37409. var normalizedY = yRotationStep / totalYRotationSteps;
  37410. var angleY = normalizedY * Math.PI * 2 * arc;
  37411. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37412. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37413. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37414. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37415. var vertex = complete.multiply(radius);
  37416. var normal = complete.divide(radius).normalize();
  37417. positions.push(vertex.x, vertex.y, vertex.z);
  37418. normals.push(normal.x, normal.y, normal.z);
  37419. uvs.push(normalizedY, normalizedZ);
  37420. }
  37421. if (zRotationStep > 0) {
  37422. var verticesCount = positions.length / 3;
  37423. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37424. indices.push((firstIndex));
  37425. indices.push((firstIndex + 1));
  37426. indices.push(firstIndex + totalYRotationSteps + 1);
  37427. indices.push((firstIndex + totalYRotationSteps + 1));
  37428. indices.push((firstIndex + 1));
  37429. indices.push((firstIndex + totalYRotationSteps + 2));
  37430. }
  37431. }
  37432. }
  37433. // Sides
  37434. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37435. // Result
  37436. var vertexData = new VertexData();
  37437. vertexData.indices = indices;
  37438. vertexData.positions = positions;
  37439. vertexData.normals = normals;
  37440. vertexData.uvs = uvs;
  37441. return vertexData;
  37442. };
  37443. /**
  37444. * Creates the VertexData for a cylinder, cone or prism
  37445. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37446. * * height sets the height (y direction) of the cylinder, optional, default 2
  37447. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37448. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37449. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37450. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37451. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37452. * * 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
  37453. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37454. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37455. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37456. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37457. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37458. * * 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)
  37459. * * 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)
  37460. * @returns the VertexData of the cylinder, cone or prism
  37461. */
  37462. VertexData.CreateCylinder = function (options) {
  37463. var height = options.height || 2;
  37464. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37465. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37466. var tessellation = options.tessellation || 24;
  37467. var subdivisions = options.subdivisions || 1;
  37468. var hasRings = options.hasRings ? true : false;
  37469. var enclose = options.enclose ? true : false;
  37470. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37471. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37472. var faceUV = options.faceUV || new Array(3);
  37473. var faceColors = options.faceColors;
  37474. // default face colors and UV if undefined
  37475. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37476. var ringNb = (hasRings) ? subdivisions : 1;
  37477. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37478. var f;
  37479. for (f = 0; f < surfaceNb; f++) {
  37480. if (faceColors && faceColors[f] === undefined) {
  37481. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37482. }
  37483. }
  37484. for (f = 0; f < surfaceNb; f++) {
  37485. if (faceUV && faceUV[f] === undefined) {
  37486. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37487. }
  37488. }
  37489. var indices = new Array();
  37490. var positions = new Array();
  37491. var normals = new Array();
  37492. var uvs = new Array();
  37493. var colors = new Array();
  37494. var angle_step = Math.PI * 2 * arc / tessellation;
  37495. var angle;
  37496. var h;
  37497. var radius;
  37498. var tan = (diameterBottom - diameterTop) / 2 / height;
  37499. var ringVertex = BABYLON.Vector3.Zero();
  37500. var ringNormal = BABYLON.Vector3.Zero();
  37501. var ringFirstVertex = BABYLON.Vector3.Zero();
  37502. var ringFirstNormal = BABYLON.Vector3.Zero();
  37503. var quadNormal = BABYLON.Vector3.Zero();
  37504. var Y = BABYLON.Axis.Y;
  37505. // positions, normals, uvs
  37506. var i;
  37507. var j;
  37508. var r;
  37509. var ringIdx = 1;
  37510. var s = 1; // surface index
  37511. var cs = 0;
  37512. var v = 0;
  37513. for (i = 0; i <= subdivisions; i++) {
  37514. h = i / subdivisions;
  37515. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37516. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37517. for (r = 0; r < ringIdx; r++) {
  37518. if (hasRings) {
  37519. s += r;
  37520. }
  37521. if (enclose) {
  37522. s += 2 * r;
  37523. }
  37524. for (j = 0; j <= tessellation; j++) {
  37525. angle = j * angle_step;
  37526. // position
  37527. ringVertex.x = Math.cos(-angle) * radius;
  37528. ringVertex.y = -height / 2 + h * height;
  37529. ringVertex.z = Math.sin(-angle) * radius;
  37530. // normal
  37531. if (diameterTop === 0 && i === subdivisions) {
  37532. // if no top cap, reuse former normals
  37533. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37534. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37535. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37536. }
  37537. else {
  37538. ringNormal.x = ringVertex.x;
  37539. ringNormal.z = ringVertex.z;
  37540. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37541. ringNormal.normalize();
  37542. }
  37543. // keep first ring vertex values for enclose
  37544. if (j === 0) {
  37545. ringFirstVertex.copyFrom(ringVertex);
  37546. ringFirstNormal.copyFrom(ringNormal);
  37547. }
  37548. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37549. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37550. if (hasRings) {
  37551. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37552. }
  37553. else {
  37554. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37555. }
  37556. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37557. if (faceColors) {
  37558. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37559. }
  37560. }
  37561. // if enclose, add four vertices and their dedicated normals
  37562. if (arc !== 1 && enclose) {
  37563. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37564. positions.push(0, ringVertex.y, 0);
  37565. positions.push(0, ringVertex.y, 0);
  37566. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37567. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37568. quadNormal.normalize();
  37569. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37570. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37571. quadNormal.normalize();
  37572. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37573. if (hasRings) {
  37574. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37575. }
  37576. else {
  37577. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37578. }
  37579. uvs.push(faceUV[s + 1].x, v);
  37580. uvs.push(faceUV[s + 1].z, v);
  37581. if (hasRings) {
  37582. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37583. }
  37584. else {
  37585. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37586. }
  37587. uvs.push(faceUV[s + 2].x, v);
  37588. uvs.push(faceUV[s + 2].z, v);
  37589. if (faceColors) {
  37590. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37591. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37592. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37593. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37594. }
  37595. }
  37596. if (cs !== s) {
  37597. cs = s;
  37598. }
  37599. }
  37600. }
  37601. // indices
  37602. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37603. var s;
  37604. i = 0;
  37605. for (s = 0; s < subdivisions; s++) {
  37606. var i0 = 0;
  37607. var i1 = 0;
  37608. var i2 = 0;
  37609. var i3 = 0;
  37610. for (j = 0; j < tessellation; j++) {
  37611. i0 = i * (e + 1) + j;
  37612. i1 = (i + 1) * (e + 1) + j;
  37613. i2 = i * (e + 1) + (j + 1);
  37614. i3 = (i + 1) * (e + 1) + (j + 1);
  37615. indices.push(i0, i1, i2);
  37616. indices.push(i3, i2, i1);
  37617. }
  37618. if (arc !== 1 && enclose) { // if enclose, add two quads
  37619. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37620. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37621. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37622. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37623. }
  37624. i = (hasRings) ? (i + 2) : (i + 1);
  37625. }
  37626. // Caps
  37627. var createCylinderCap = function (isTop) {
  37628. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37629. if (radius === 0) {
  37630. return;
  37631. }
  37632. // Cap positions, normals & uvs
  37633. var angle;
  37634. var circleVector;
  37635. var i;
  37636. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37637. var c = null;
  37638. if (faceColors) {
  37639. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37640. }
  37641. // cap center
  37642. var vbase = positions.length / 3;
  37643. var offset = isTop ? height / 2 : -height / 2;
  37644. var center = new BABYLON.Vector3(0, offset, 0);
  37645. positions.push(center.x, center.y, center.z);
  37646. normals.push(0, isTop ? 1 : -1, 0);
  37647. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37648. if (c) {
  37649. colors.push(c.r, c.g, c.b, c.a);
  37650. }
  37651. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37652. for (i = 0; i <= tessellation; i++) {
  37653. angle = Math.PI * 2 * i * arc / tessellation;
  37654. var cos = Math.cos(-angle);
  37655. var sin = Math.sin(-angle);
  37656. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37657. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37658. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37659. normals.push(0, isTop ? 1 : -1, 0);
  37660. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37661. if (c) {
  37662. colors.push(c.r, c.g, c.b, c.a);
  37663. }
  37664. }
  37665. // Cap indices
  37666. for (i = 0; i < tessellation; i++) {
  37667. if (!isTop) {
  37668. indices.push(vbase);
  37669. indices.push(vbase + (i + 1));
  37670. indices.push(vbase + (i + 2));
  37671. }
  37672. else {
  37673. indices.push(vbase);
  37674. indices.push(vbase + (i + 2));
  37675. indices.push(vbase + (i + 1));
  37676. }
  37677. }
  37678. };
  37679. // add caps to geometry
  37680. createCylinderCap(false);
  37681. createCylinderCap(true);
  37682. // Sides
  37683. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37684. var vertexData = new VertexData();
  37685. vertexData.indices = indices;
  37686. vertexData.positions = positions;
  37687. vertexData.normals = normals;
  37688. vertexData.uvs = uvs;
  37689. if (faceColors) {
  37690. vertexData.colors = colors;
  37691. }
  37692. return vertexData;
  37693. };
  37694. /**
  37695. * Creates the VertexData for a torus
  37696. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37697. * * diameter the diameter of the torus, optional default 1
  37698. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37699. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37700. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37701. * * 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)
  37702. * * 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)
  37703. * @returns the VertexData of the torus
  37704. */
  37705. VertexData.CreateTorus = function (options) {
  37706. var indices = [];
  37707. var positions = [];
  37708. var normals = [];
  37709. var uvs = [];
  37710. var diameter = options.diameter || 1;
  37711. var thickness = options.thickness || 0.5;
  37712. var tessellation = options.tessellation || 16;
  37713. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37714. var stride = tessellation + 1;
  37715. for (var i = 0; i <= tessellation; i++) {
  37716. var u = i / tessellation;
  37717. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37718. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37719. for (var j = 0; j <= tessellation; j++) {
  37720. var v = 1 - j / tessellation;
  37721. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37722. var dx = Math.cos(innerAngle);
  37723. var dy = Math.sin(innerAngle);
  37724. // Create a vertex.
  37725. var normal = new BABYLON.Vector3(dx, dy, 0);
  37726. var position = normal.scale(thickness / 2);
  37727. var textureCoordinate = new BABYLON.Vector2(u, v);
  37728. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37729. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37730. positions.push(position.x, position.y, position.z);
  37731. normals.push(normal.x, normal.y, normal.z);
  37732. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37733. // And create indices for two triangles.
  37734. var nextI = (i + 1) % stride;
  37735. var nextJ = (j + 1) % stride;
  37736. indices.push(i * stride + j);
  37737. indices.push(i * stride + nextJ);
  37738. indices.push(nextI * stride + j);
  37739. indices.push(i * stride + nextJ);
  37740. indices.push(nextI * stride + nextJ);
  37741. indices.push(nextI * stride + j);
  37742. }
  37743. }
  37744. // Sides
  37745. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37746. // Result
  37747. var vertexData = new VertexData();
  37748. vertexData.indices = indices;
  37749. vertexData.positions = positions;
  37750. vertexData.normals = normals;
  37751. vertexData.uvs = uvs;
  37752. return vertexData;
  37753. };
  37754. /**
  37755. * Creates the VertexData of the LineSystem
  37756. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37757. * - lines an array of lines, each line being an array of successive Vector3
  37758. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37759. * @returns the VertexData of the LineSystem
  37760. */
  37761. VertexData.CreateLineSystem = function (options) {
  37762. var indices = [];
  37763. var positions = [];
  37764. var lines = options.lines;
  37765. var colors = options.colors;
  37766. var vertexColors = [];
  37767. var idx = 0;
  37768. for (var l = 0; l < lines.length; l++) {
  37769. var points = lines[l];
  37770. for (var index = 0; index < points.length; index++) {
  37771. positions.push(points[index].x, points[index].y, points[index].z);
  37772. if (colors) {
  37773. var color = colors[l];
  37774. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37775. }
  37776. if (index > 0) {
  37777. indices.push(idx - 1);
  37778. indices.push(idx);
  37779. }
  37780. idx++;
  37781. }
  37782. }
  37783. var vertexData = new VertexData();
  37784. vertexData.indices = indices;
  37785. vertexData.positions = positions;
  37786. if (colors) {
  37787. vertexData.colors = vertexColors;
  37788. }
  37789. return vertexData;
  37790. };
  37791. /**
  37792. * Create the VertexData for a DashedLines
  37793. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37794. * - points an array successive Vector3
  37795. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37796. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37797. * - dashNb the intended total number of dashes, optional, default 200
  37798. * @returns the VertexData for the DashedLines
  37799. */
  37800. VertexData.CreateDashedLines = function (options) {
  37801. var dashSize = options.dashSize || 3;
  37802. var gapSize = options.gapSize || 1;
  37803. var dashNb = options.dashNb || 200;
  37804. var points = options.points;
  37805. var positions = new Array();
  37806. var indices = new Array();
  37807. var curvect = BABYLON.Vector3.Zero();
  37808. var lg = 0;
  37809. var nb = 0;
  37810. var shft = 0;
  37811. var dashshft = 0;
  37812. var curshft = 0;
  37813. var idx = 0;
  37814. var i = 0;
  37815. for (i = 0; i < points.length - 1; i++) {
  37816. points[i + 1].subtractToRef(points[i], curvect);
  37817. lg += curvect.length();
  37818. }
  37819. shft = lg / dashNb;
  37820. dashshft = dashSize * shft / (dashSize + gapSize);
  37821. for (i = 0; i < points.length - 1; i++) {
  37822. points[i + 1].subtractToRef(points[i], curvect);
  37823. nb = Math.floor(curvect.length() / shft);
  37824. curvect.normalize();
  37825. for (var j = 0; j < nb; j++) {
  37826. curshft = shft * j;
  37827. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37828. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37829. indices.push(idx, idx + 1);
  37830. idx += 2;
  37831. }
  37832. }
  37833. // Result
  37834. var vertexData = new VertexData();
  37835. vertexData.positions = positions;
  37836. vertexData.indices = indices;
  37837. return vertexData;
  37838. };
  37839. /**
  37840. * Creates the VertexData for a Ground
  37841. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37842. * - width the width (x direction) of the ground, optional, default 1
  37843. * - height the height (z direction) of the ground, optional, default 1
  37844. * - subdivisions the number of subdivisions per side, optional, default 1
  37845. * @returns the VertexData of the Ground
  37846. */
  37847. VertexData.CreateGround = function (options) {
  37848. var indices = [];
  37849. var positions = [];
  37850. var normals = [];
  37851. var uvs = [];
  37852. var row, col;
  37853. var width = options.width || 1;
  37854. var height = options.height || 1;
  37855. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37856. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37857. for (row = 0; row <= subdivisionsY; row++) {
  37858. for (col = 0; col <= subdivisionsX; col++) {
  37859. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37860. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37861. positions.push(position.x, position.y, position.z);
  37862. normals.push(normal.x, normal.y, normal.z);
  37863. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37864. }
  37865. }
  37866. for (row = 0; row < subdivisionsY; row++) {
  37867. for (col = 0; col < subdivisionsX; col++) {
  37868. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37869. indices.push(col + 1 + row * (subdivisionsX + 1));
  37870. indices.push(col + row * (subdivisionsX + 1));
  37871. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37872. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37873. indices.push(col + row * (subdivisionsX + 1));
  37874. }
  37875. }
  37876. // Result
  37877. var vertexData = new VertexData();
  37878. vertexData.indices = indices;
  37879. vertexData.positions = positions;
  37880. vertexData.normals = normals;
  37881. vertexData.uvs = uvs;
  37882. return vertexData;
  37883. };
  37884. /**
  37885. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37886. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37887. * * xmin the ground minimum X coordinate, optional, default -1
  37888. * * zmin the ground minimum Z coordinate, optional, default -1
  37889. * * xmax the ground maximum X coordinate, optional, default 1
  37890. * * zmax the ground maximum Z coordinate, optional, default 1
  37891. * * 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}
  37892. * * 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}
  37893. * @returns the VertexData of the TiledGround
  37894. */
  37895. VertexData.CreateTiledGround = function (options) {
  37896. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37897. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37898. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37899. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37900. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37901. var precision = options.precision || { w: 1, h: 1 };
  37902. var indices = new Array();
  37903. var positions = new Array();
  37904. var normals = new Array();
  37905. var uvs = new Array();
  37906. var row, col, tileRow, tileCol;
  37907. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37908. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37909. precision.w = (precision.w < 1) ? 1 : precision.w;
  37910. precision.h = (precision.h < 1) ? 1 : precision.h;
  37911. var tileSize = {
  37912. 'w': (xmax - xmin) / subdivisions.w,
  37913. 'h': (zmax - zmin) / subdivisions.h
  37914. };
  37915. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37916. // Indices
  37917. var base = positions.length / 3;
  37918. var rowLength = precision.w + 1;
  37919. for (row = 0; row < precision.h; row++) {
  37920. for (col = 0; col < precision.w; col++) {
  37921. var square = [
  37922. base + col + row * rowLength,
  37923. base + (col + 1) + row * rowLength,
  37924. base + (col + 1) + (row + 1) * rowLength,
  37925. base + col + (row + 1) * rowLength
  37926. ];
  37927. indices.push(square[1]);
  37928. indices.push(square[2]);
  37929. indices.push(square[3]);
  37930. indices.push(square[0]);
  37931. indices.push(square[1]);
  37932. indices.push(square[3]);
  37933. }
  37934. }
  37935. // Position, normals and uvs
  37936. var position = BABYLON.Vector3.Zero();
  37937. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37938. for (row = 0; row <= precision.h; row++) {
  37939. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37940. for (col = 0; col <= precision.w; col++) {
  37941. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37942. position.y = 0;
  37943. positions.push(position.x, position.y, position.z);
  37944. normals.push(normal.x, normal.y, normal.z);
  37945. uvs.push(col / precision.w, row / precision.h);
  37946. }
  37947. }
  37948. }
  37949. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37950. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37951. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37952. }
  37953. }
  37954. // Result
  37955. var vertexData = new VertexData();
  37956. vertexData.indices = indices;
  37957. vertexData.positions = positions;
  37958. vertexData.normals = normals;
  37959. vertexData.uvs = uvs;
  37960. return vertexData;
  37961. };
  37962. /**
  37963. * Creates the VertexData of the Ground designed from a heightmap
  37964. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37965. * * width the width (x direction) of the ground
  37966. * * height the height (z direction) of the ground
  37967. * * subdivisions the number of subdivisions per side
  37968. * * minHeight the minimum altitude on the ground, optional, default 0
  37969. * * maxHeight the maximum altitude on the ground, optional default 1
  37970. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37971. * * buffer the array holding the image color data
  37972. * * bufferWidth the width of image
  37973. * * bufferHeight the height of image
  37974. * @returns the VertexData of the Ground designed from a heightmap
  37975. */
  37976. VertexData.CreateGroundFromHeightMap = function (options) {
  37977. var indices = [];
  37978. var positions = [];
  37979. var normals = [];
  37980. var uvs = [];
  37981. var row, col;
  37982. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37983. // Vertices
  37984. for (row = 0; row <= options.subdivisions; row++) {
  37985. for (col = 0; col <= options.subdivisions; col++) {
  37986. 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));
  37987. // Compute height
  37988. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37989. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37990. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37991. var r = options.buffer[pos] / 255.0;
  37992. var g = options.buffer[pos + 1] / 255.0;
  37993. var b = options.buffer[pos + 2] / 255.0;
  37994. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37995. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37996. // Add vertex
  37997. positions.push(position.x, position.y, position.z);
  37998. normals.push(0, 0, 0);
  37999. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38000. }
  38001. }
  38002. // Indices
  38003. for (row = 0; row < options.subdivisions; row++) {
  38004. for (col = 0; col < options.subdivisions; col++) {
  38005. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38006. indices.push(col + 1 + row * (options.subdivisions + 1));
  38007. indices.push(col + row * (options.subdivisions + 1));
  38008. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38009. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38010. indices.push(col + row * (options.subdivisions + 1));
  38011. }
  38012. }
  38013. // Normals
  38014. VertexData.ComputeNormals(positions, indices, normals);
  38015. // Result
  38016. var vertexData = new VertexData();
  38017. vertexData.indices = indices;
  38018. vertexData.positions = positions;
  38019. vertexData.normals = normals;
  38020. vertexData.uvs = uvs;
  38021. return vertexData;
  38022. };
  38023. /**
  38024. * Creates the VertexData for a Plane
  38025. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38026. * * size sets the width and height of the plane to the value of size, optional default 1
  38027. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38028. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38029. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38030. * * 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)
  38031. * * 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)
  38032. * @returns the VertexData of the box
  38033. */
  38034. VertexData.CreatePlane = function (options) {
  38035. var indices = [];
  38036. var positions = [];
  38037. var normals = [];
  38038. var uvs = [];
  38039. var width = options.width || options.size || 1;
  38040. var height = options.height || options.size || 1;
  38041. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38042. // Vertices
  38043. var halfWidth = width / 2.0;
  38044. var halfHeight = height / 2.0;
  38045. positions.push(-halfWidth, -halfHeight, 0);
  38046. normals.push(0, 0, -1.0);
  38047. uvs.push(0.0, 0.0);
  38048. positions.push(halfWidth, -halfHeight, 0);
  38049. normals.push(0, 0, -1.0);
  38050. uvs.push(1.0, 0.0);
  38051. positions.push(halfWidth, halfHeight, 0);
  38052. normals.push(0, 0, -1.0);
  38053. uvs.push(1.0, 1.0);
  38054. positions.push(-halfWidth, halfHeight, 0);
  38055. normals.push(0, 0, -1.0);
  38056. uvs.push(0.0, 1.0);
  38057. // Indices
  38058. indices.push(0);
  38059. indices.push(1);
  38060. indices.push(2);
  38061. indices.push(0);
  38062. indices.push(2);
  38063. indices.push(3);
  38064. // Sides
  38065. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38066. // Result
  38067. var vertexData = new VertexData();
  38068. vertexData.indices = indices;
  38069. vertexData.positions = positions;
  38070. vertexData.normals = normals;
  38071. vertexData.uvs = uvs;
  38072. return vertexData;
  38073. };
  38074. /**
  38075. * Creates the VertexData of the Disc or regular Polygon
  38076. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38077. * * radius the radius of the disc, optional default 0.5
  38078. * * tessellation the number of polygon sides, optional, default 64
  38079. * * 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
  38080. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38081. * * 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)
  38082. * * 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)
  38083. * @returns the VertexData of the box
  38084. */
  38085. VertexData.CreateDisc = function (options) {
  38086. var positions = new Array();
  38087. var indices = new Array();
  38088. var normals = new Array();
  38089. var uvs = new Array();
  38090. var radius = options.radius || 0.5;
  38091. var tessellation = options.tessellation || 64;
  38092. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38093. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38094. // positions and uvs
  38095. positions.push(0, 0, 0); // disc center first
  38096. uvs.push(0.5, 0.5);
  38097. var theta = Math.PI * 2 * arc;
  38098. var step = theta / tessellation;
  38099. for (var a = 0; a < theta; a += step) {
  38100. var x = Math.cos(a);
  38101. var y = Math.sin(a);
  38102. var u = (x + 1) / 2;
  38103. var v = (1 - y) / 2;
  38104. positions.push(radius * x, radius * y, 0);
  38105. uvs.push(u, v);
  38106. }
  38107. if (arc === 1) {
  38108. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38109. uvs.push(uvs[2], uvs[3]);
  38110. }
  38111. //indices
  38112. var vertexNb = positions.length / 3;
  38113. for (var i = 1; i < vertexNb - 1; i++) {
  38114. indices.push(i + 1, 0, i);
  38115. }
  38116. // result
  38117. VertexData.ComputeNormals(positions, indices, normals);
  38118. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38119. var vertexData = new VertexData();
  38120. vertexData.indices = indices;
  38121. vertexData.positions = positions;
  38122. vertexData.normals = normals;
  38123. vertexData.uvs = uvs;
  38124. return vertexData;
  38125. };
  38126. /**
  38127. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38128. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38129. * @param polygon a mesh built from polygonTriangulation.build()
  38130. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38131. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38132. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38133. * @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)
  38134. * @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)
  38135. * @returns the VertexData of the Polygon
  38136. */
  38137. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38138. var faceUV = fUV || new Array(3);
  38139. var faceColors = fColors;
  38140. var colors = [];
  38141. // default face colors and UV if undefined
  38142. for (var f = 0; f < 3; f++) {
  38143. if (faceUV[f] === undefined) {
  38144. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38145. }
  38146. if (faceColors && faceColors[f] === undefined) {
  38147. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38148. }
  38149. }
  38150. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38151. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38152. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38153. var indices = polygon.getIndices();
  38154. // set face colours and textures
  38155. var idx = 0;
  38156. var face = 0;
  38157. for (var index = 0; index < normals.length; index += 3) {
  38158. //Edge Face no. 1
  38159. if (Math.abs(normals[index + 1]) < 0.001) {
  38160. face = 1;
  38161. }
  38162. //Top Face no. 0
  38163. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38164. face = 0;
  38165. }
  38166. //Bottom Face no. 2
  38167. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38168. face = 2;
  38169. }
  38170. idx = index / 3;
  38171. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38172. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38173. if (faceColors) {
  38174. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38175. }
  38176. }
  38177. // sides
  38178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38179. // Result
  38180. var vertexData = new VertexData();
  38181. vertexData.indices = indices;
  38182. vertexData.positions = positions;
  38183. vertexData.normals = normals;
  38184. vertexData.uvs = uvs;
  38185. if (faceColors) {
  38186. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38187. vertexData.colors = totalColors;
  38188. }
  38189. return vertexData;
  38190. };
  38191. /**
  38192. * Creates the VertexData of the IcoSphere
  38193. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38194. * * radius the radius of the IcoSphere, optional default 1
  38195. * * radiusX allows stretching in the x direction, optional, default radius
  38196. * * radiusY allows stretching in the y direction, optional, default radius
  38197. * * radiusZ allows stretching in the z direction, optional, default radius
  38198. * * flat when true creates a flat shaded mesh, optional, default true
  38199. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38200. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38201. * * 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)
  38202. * * 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)
  38203. * @returns the VertexData of the IcoSphere
  38204. */
  38205. VertexData.CreateIcoSphere = function (options) {
  38206. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38207. var radius = options.radius || 1;
  38208. var flat = (options.flat === undefined) ? true : options.flat;
  38209. var subdivisions = options.subdivisions || 4;
  38210. var radiusX = options.radiusX || radius;
  38211. var radiusY = options.radiusY || radius;
  38212. var radiusZ = options.radiusZ || radius;
  38213. var t = (1 + Math.sqrt(5)) / 2;
  38214. // 12 vertex x,y,z
  38215. var ico_vertices = [
  38216. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38217. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38218. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38219. ];
  38220. // index of 3 vertex makes a face of icopshere
  38221. var ico_indices = [
  38222. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38223. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38224. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38225. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38226. ];
  38227. // vertex for uv have aliased position, not for UV
  38228. var vertices_unalias_id = [
  38229. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38230. // vertex alias
  38231. 0,
  38232. 2,
  38233. 3,
  38234. 3,
  38235. 3,
  38236. 4,
  38237. 7,
  38238. 8,
  38239. 9,
  38240. 9,
  38241. 10,
  38242. 11 // 23: B + 12
  38243. ];
  38244. // uv as integer step (not pixels !)
  38245. var ico_vertexuv = [
  38246. 5, 1, 3, 1, 6, 4, 0, 0,
  38247. 5, 3, 4, 2, 2, 2, 4, 0,
  38248. 2, 0, 1, 1, 6, 0, 6, 2,
  38249. // vertex alias (for same vertex on different faces)
  38250. 0, 4,
  38251. 3, 3,
  38252. 4, 4,
  38253. 3, 1,
  38254. 4, 2,
  38255. 4, 4,
  38256. 0, 2,
  38257. 1, 1,
  38258. 2, 2,
  38259. 3, 3,
  38260. 1, 3,
  38261. 2, 4 // 23: B + 12
  38262. ];
  38263. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38264. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38265. // First island of uv mapping
  38266. // v = 4h 3+ 2
  38267. // v = 3h 9+ 4
  38268. // v = 2h 9+ 5 B
  38269. // v = 1h 9 1 0
  38270. // v = 0h 3 8 7 A
  38271. // u = 0 1 2 3 4 5 6 *a
  38272. // Second island of uv mapping
  38273. // v = 4h 0+ B+ 4+
  38274. // v = 3h A+ 2+
  38275. // v = 2h 7+ 6 3+
  38276. // v = 1h 8+ 3+
  38277. // v = 0h
  38278. // u = 0 1 2 3 4 5 6 *a
  38279. // Face layout on texture UV mapping
  38280. // ============
  38281. // \ 4 /\ 16 / ======
  38282. // \ / \ / /\ 11 /
  38283. // \/ 7 \/ / \ /
  38284. // ======= / 10 \/
  38285. // /\ 17 /\ =======
  38286. // / \ / \ \ 15 /\
  38287. // / 8 \/ 12 \ \ / \
  38288. // ============ \/ 6 \
  38289. // \ 18 /\ ============
  38290. // \ / \ \ 5 /\ 0 /
  38291. // \/ 13 \ \ / \ /
  38292. // ======= \/ 1 \/
  38293. // =============
  38294. // /\ 19 /\ 2 /\
  38295. // / \ / \ / \
  38296. // / 14 \/ 9 \/ 3 \
  38297. // ===================
  38298. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38299. var ustep = 138 / 1024;
  38300. var vstep = 239 / 1024;
  38301. var uoffset = 60 / 1024;
  38302. var voffset = 26 / 1024;
  38303. // Second island should have margin, not to touch the first island
  38304. // avoid any borderline artefact in pixel rounding
  38305. var island_u_offset = -40 / 1024;
  38306. var island_v_offset = +20 / 1024;
  38307. // face is either island 0 or 1 :
  38308. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38309. var island = [
  38310. 0, 0, 0, 0, 1,
  38311. 0, 0, 1, 1, 0,
  38312. 0, 0, 1, 1, 0,
  38313. 0, 1, 1, 1, 0 // 15 - 19
  38314. ];
  38315. var indices = new Array();
  38316. var positions = new Array();
  38317. var normals = new Array();
  38318. var uvs = new Array();
  38319. var current_indice = 0;
  38320. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38321. var face_vertex_pos = new Array(3);
  38322. var face_vertex_uv = new Array(3);
  38323. var v012;
  38324. for (v012 = 0; v012 < 3; v012++) {
  38325. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38326. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38327. }
  38328. // create all with normals
  38329. for (var face = 0; face < 20; face++) {
  38330. // 3 vertex per face
  38331. for (v012 = 0; v012 < 3; v012++) {
  38332. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38333. var v_id = ico_indices[3 * face + v012];
  38334. // vertex have 3D position (x,y,z)
  38335. 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]);
  38336. // Normalize to get normal, then scale to radius
  38337. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38338. // uv Coordinates from vertex ID
  38339. 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);
  38340. }
  38341. // Subdivide the face (interpolate pos, norm, uv)
  38342. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38343. // - norm is linear interpolation of vertex corner normal
  38344. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38345. // - uv is linear interpolation
  38346. //
  38347. // Topology is as below for sub-divide by 2
  38348. // vertex shown as v0,v1,v2
  38349. // interp index is i1 to progress in range [v0,v1[
  38350. // interp index is i2 to progress in range [v0,v2[
  38351. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38352. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38353. //
  38354. //
  38355. // i2 v2
  38356. // ^ ^
  38357. // / / \
  38358. // / / \
  38359. // / / \
  38360. // / / (0,1) \
  38361. // / #---------\
  38362. // / / \ (0,0)'/ \
  38363. // / / \ / \
  38364. // / / \ / \
  38365. // / / (0,0) \ / (1,0) \
  38366. // / #---------#---------\
  38367. // v0 v1
  38368. //
  38369. // --------------------> i1
  38370. //
  38371. // interp of (i1,i2):
  38372. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38373. // along i1 : lerp(x0,x1, i1/(S-i2))
  38374. //
  38375. // centroid of triangle is needed to get help normal computation
  38376. // (c1,c2) are used for centroid location
  38377. var interp_vertex = function (i1, i2, c1, c2) {
  38378. // vertex is interpolated from
  38379. // - face_vertex_pos[0..2]
  38380. // - face_vertex_uv[0..2]
  38381. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38382. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38383. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38384. pos_interp.normalize();
  38385. var vertex_normal;
  38386. if (flat) {
  38387. // in flat mode, recalculate normal as face centroid normal
  38388. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38389. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38390. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38391. }
  38392. else {
  38393. // in smooth mode, recalculate normal from each single vertex position
  38394. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38395. }
  38396. // Vertex normal need correction due to X,Y,Z radius scaling
  38397. vertex_normal.x /= radiusX;
  38398. vertex_normal.y /= radiusY;
  38399. vertex_normal.z /= radiusZ;
  38400. vertex_normal.normalize();
  38401. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38402. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38403. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38404. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38405. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38406. uvs.push(uv_interp.x, uv_interp.y);
  38407. // push each vertex has member of a face
  38408. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38409. indices.push(current_indice);
  38410. current_indice++;
  38411. };
  38412. for (var i2 = 0; i2 < subdivisions; i2++) {
  38413. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38414. // face : (i1,i2) for /\ :
  38415. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38416. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38417. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38418. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38419. if (i1 + i2 + 1 < subdivisions) {
  38420. // face : (i1,i2)' for \/ :
  38421. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38422. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38423. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38424. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38425. }
  38426. }
  38427. }
  38428. }
  38429. // Sides
  38430. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38431. // Result
  38432. var vertexData = new VertexData();
  38433. vertexData.indices = indices;
  38434. vertexData.positions = positions;
  38435. vertexData.normals = normals;
  38436. vertexData.uvs = uvs;
  38437. return vertexData;
  38438. };
  38439. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38440. /**
  38441. * Creates the VertexData for a Polyhedron
  38442. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38443. * * type provided types are:
  38444. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38445. * * 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)
  38446. * * size the size of the IcoSphere, optional default 1
  38447. * * sizeX allows stretching in the x direction, optional, default size
  38448. * * sizeY allows stretching in the y direction, optional, default size
  38449. * * sizeZ allows stretching in the z direction, optional, default size
  38450. * * 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
  38451. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38452. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38453. * * flat when true creates a flat shaded mesh, optional, default true
  38454. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38455. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38456. * * 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)
  38457. * * 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)
  38458. * @returns the VertexData of the Polyhedron
  38459. */
  38460. VertexData.CreatePolyhedron = function (options) {
  38461. // provided polyhedron types :
  38462. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38463. // 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)
  38464. var polyhedra = [];
  38465. 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]] };
  38466. 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]] };
  38467. polyhedra[2] = {
  38468. 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]],
  38469. 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]]
  38470. };
  38471. polyhedra[3] = {
  38472. 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]],
  38473. 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]]
  38474. };
  38475. polyhedra[4] = {
  38476. 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]],
  38477. 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]]
  38478. };
  38479. 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]] };
  38480. 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]] };
  38481. 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]] };
  38482. 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]] };
  38483. 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]] };
  38484. 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]] };
  38485. 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]] };
  38486. 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]] };
  38487. 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]] };
  38488. polyhedra[14] = {
  38489. 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]],
  38490. 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]]
  38491. };
  38492. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38493. var size = options.size;
  38494. var sizeX = options.sizeX || size || 1;
  38495. var sizeY = options.sizeY || size || 1;
  38496. var sizeZ = options.sizeZ || size || 1;
  38497. var data = options.custom || polyhedra[type];
  38498. var nbfaces = data.face.length;
  38499. var faceUV = options.faceUV || new Array(nbfaces);
  38500. var faceColors = options.faceColors;
  38501. var flat = (options.flat === undefined) ? true : options.flat;
  38502. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38503. var positions = new Array();
  38504. var indices = new Array();
  38505. var normals = new Array();
  38506. var uvs = new Array();
  38507. var colors = new Array();
  38508. var index = 0;
  38509. var faceIdx = 0; // face cursor in the array "indexes"
  38510. var indexes = new Array();
  38511. var i = 0;
  38512. var f = 0;
  38513. var u, v, ang, x, y, tmp;
  38514. // default face colors and UV if undefined
  38515. if (flat) {
  38516. for (f = 0; f < nbfaces; f++) {
  38517. if (faceColors && faceColors[f] === undefined) {
  38518. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38519. }
  38520. if (faceUV && faceUV[f] === undefined) {
  38521. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38522. }
  38523. }
  38524. }
  38525. if (!flat) {
  38526. for (i = 0; i < data.vertex.length; i++) {
  38527. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38528. uvs.push(0, 0);
  38529. }
  38530. for (f = 0; f < nbfaces; f++) {
  38531. for (i = 0; i < data.face[f].length - 2; i++) {
  38532. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38533. }
  38534. }
  38535. }
  38536. else {
  38537. for (f = 0; f < nbfaces; f++) {
  38538. var fl = data.face[f].length; // number of vertices of the current face
  38539. ang = 2 * Math.PI / fl;
  38540. x = 0.5 * Math.tan(ang / 2);
  38541. y = 0.5;
  38542. // positions, uvs, colors
  38543. for (i = 0; i < fl; i++) {
  38544. // positions
  38545. 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);
  38546. indexes.push(index);
  38547. index++;
  38548. // uvs
  38549. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38550. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38551. uvs.push(u, v);
  38552. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38553. y = x * Math.sin(ang) + y * Math.cos(ang);
  38554. x = tmp;
  38555. // colors
  38556. if (faceColors) {
  38557. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38558. }
  38559. }
  38560. // indices from indexes
  38561. for (i = 0; i < fl - 2; i++) {
  38562. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38563. }
  38564. faceIdx += fl;
  38565. }
  38566. }
  38567. VertexData.ComputeNormals(positions, indices, normals);
  38568. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38569. var vertexData = new VertexData();
  38570. vertexData.positions = positions;
  38571. vertexData.indices = indices;
  38572. vertexData.normals = normals;
  38573. vertexData.uvs = uvs;
  38574. if (faceColors && flat) {
  38575. vertexData.colors = colors;
  38576. }
  38577. return vertexData;
  38578. };
  38579. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38580. /**
  38581. * Creates the VertexData for a TorusKnot
  38582. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38583. * * radius the radius of the torus knot, optional, default 2
  38584. * * tube the thickness of the tube, optional, default 0.5
  38585. * * radialSegments the number of sides on each tube segments, optional, default 32
  38586. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38587. * * p the number of windings around the z axis, optional, default 2
  38588. * * q the number of windings around the x axis, optional, default 3
  38589. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38590. * * 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)
  38591. * * 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)
  38592. * @returns the VertexData of the Torus Knot
  38593. */
  38594. VertexData.CreateTorusKnot = function (options) {
  38595. var indices = new Array();
  38596. var positions = new Array();
  38597. var normals = new Array();
  38598. var uvs = new Array();
  38599. var radius = options.radius || 2;
  38600. var tube = options.tube || 0.5;
  38601. var radialSegments = options.radialSegments || 32;
  38602. var tubularSegments = options.tubularSegments || 32;
  38603. var p = options.p || 2;
  38604. var q = options.q || 3;
  38605. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38606. // Helper
  38607. var getPos = function (angle) {
  38608. var cu = Math.cos(angle);
  38609. var su = Math.sin(angle);
  38610. var quOverP = q / p * angle;
  38611. var cs = Math.cos(quOverP);
  38612. var tx = radius * (2 + cs) * 0.5 * cu;
  38613. var ty = radius * (2 + cs) * su * 0.5;
  38614. var tz = radius * Math.sin(quOverP) * 0.5;
  38615. return new BABYLON.Vector3(tx, ty, tz);
  38616. };
  38617. // Vertices
  38618. var i;
  38619. var j;
  38620. for (i = 0; i <= radialSegments; i++) {
  38621. var modI = i % radialSegments;
  38622. var u = modI / radialSegments * 2 * p * Math.PI;
  38623. var p1 = getPos(u);
  38624. var p2 = getPos(u + 0.01);
  38625. var tang = p2.subtract(p1);
  38626. var n = p2.add(p1);
  38627. var bitan = BABYLON.Vector3.Cross(tang, n);
  38628. n = BABYLON.Vector3.Cross(bitan, tang);
  38629. bitan.normalize();
  38630. n.normalize();
  38631. for (j = 0; j < tubularSegments; j++) {
  38632. var modJ = j % tubularSegments;
  38633. var v = modJ / tubularSegments * 2 * Math.PI;
  38634. var cx = -tube * Math.cos(v);
  38635. var cy = tube * Math.sin(v);
  38636. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38637. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38638. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38639. uvs.push(i / radialSegments);
  38640. uvs.push(j / tubularSegments);
  38641. }
  38642. }
  38643. for (i = 0; i < radialSegments; i++) {
  38644. for (j = 0; j < tubularSegments; j++) {
  38645. var jNext = (j + 1) % tubularSegments;
  38646. var a = i * tubularSegments + j;
  38647. var b = (i + 1) * tubularSegments + j;
  38648. var c = (i + 1) * tubularSegments + jNext;
  38649. var d = i * tubularSegments + jNext;
  38650. indices.push(d);
  38651. indices.push(b);
  38652. indices.push(a);
  38653. indices.push(d);
  38654. indices.push(c);
  38655. indices.push(b);
  38656. }
  38657. }
  38658. // Normals
  38659. VertexData.ComputeNormals(positions, indices, normals);
  38660. // Sides
  38661. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38662. // Result
  38663. var vertexData = new VertexData();
  38664. vertexData.indices = indices;
  38665. vertexData.positions = positions;
  38666. vertexData.normals = normals;
  38667. vertexData.uvs = uvs;
  38668. return vertexData;
  38669. };
  38670. // Tools
  38671. /**
  38672. * Compute normals for given positions and indices
  38673. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38674. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38675. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38676. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38677. * * facetNormals : optional array of facet normals (vector3)
  38678. * * facetPositions : optional array of facet positions (vector3)
  38679. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38680. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38681. * * bInfo : optional bounding info, required for facetPartitioning computation
  38682. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38683. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38684. * * useRightHandedSystem: optional boolean to for right handed system computation
  38685. * * depthSort : optional boolean to enable the facet depth sort computation
  38686. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38687. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38688. */
  38689. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38690. // temporary scalar variables
  38691. var index = 0; // facet index
  38692. var p1p2x = 0.0; // p1p2 vector x coordinate
  38693. var p1p2y = 0.0; // p1p2 vector y coordinate
  38694. var p1p2z = 0.0; // p1p2 vector z coordinate
  38695. var p3p2x = 0.0; // p3p2 vector x coordinate
  38696. var p3p2y = 0.0; // p3p2 vector y coordinate
  38697. var p3p2z = 0.0; // p3p2 vector z coordinate
  38698. var faceNormalx = 0.0; // facet normal x coordinate
  38699. var faceNormaly = 0.0; // facet normal y coordinate
  38700. var faceNormalz = 0.0; // facet normal z coordinate
  38701. var length = 0.0; // facet normal length before normalization
  38702. var v1x = 0; // vector1 x index in the positions array
  38703. var v1y = 0; // vector1 y index in the positions array
  38704. var v1z = 0; // vector1 z index in the positions array
  38705. var v2x = 0; // vector2 x index in the positions array
  38706. var v2y = 0; // vector2 y index in the positions array
  38707. var v2z = 0; // vector2 z index in the positions array
  38708. var v3x = 0; // vector3 x index in the positions array
  38709. var v3y = 0; // vector3 y index in the positions array
  38710. var v3z = 0; // vector3 z index in the positions array
  38711. var computeFacetNormals = false;
  38712. var computeFacetPositions = false;
  38713. var computeFacetPartitioning = false;
  38714. var computeDepthSort = false;
  38715. var faceNormalSign = 1;
  38716. var ratio = 0;
  38717. var distanceTo = null;
  38718. if (options) {
  38719. computeFacetNormals = (options.facetNormals) ? true : false;
  38720. computeFacetPositions = (options.facetPositions) ? true : false;
  38721. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38722. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38723. ratio = options.ratio || 0;
  38724. computeDepthSort = (options.depthSort) ? true : false;
  38725. distanceTo = (options.distanceTo);
  38726. if (computeDepthSort) {
  38727. if (distanceTo === undefined) {
  38728. distanceTo = BABYLON.Vector3.Zero();
  38729. }
  38730. var depthSortedFacets = options.depthSortedFacets;
  38731. }
  38732. }
  38733. // facetPartitioning reinit if needed
  38734. var xSubRatio = 0;
  38735. var ySubRatio = 0;
  38736. var zSubRatio = 0;
  38737. var subSq = 0;
  38738. if (computeFacetPartitioning && options && options.bbSize) {
  38739. var ox = 0; // X partitioning index for facet position
  38740. var oy = 0; // Y partinioning index for facet position
  38741. var oz = 0; // Z partinioning index for facet position
  38742. var b1x = 0; // X partitioning index for facet v1 vertex
  38743. var b1y = 0; // Y partitioning index for facet v1 vertex
  38744. var b1z = 0; // z partitioning index for facet v1 vertex
  38745. var b2x = 0; // X partitioning index for facet v2 vertex
  38746. var b2y = 0; // Y partitioning index for facet v2 vertex
  38747. var b2z = 0; // Z partitioning index for facet v2 vertex
  38748. var b3x = 0; // X partitioning index for facet v3 vertex
  38749. var b3y = 0; // Y partitioning index for facet v3 vertex
  38750. var b3z = 0; // Z partitioning index for facet v3 vertex
  38751. var block_idx_o = 0; // facet barycenter block index
  38752. var block_idx_v1 = 0; // v1 vertex block index
  38753. var block_idx_v2 = 0; // v2 vertex block index
  38754. var block_idx_v3 = 0; // v3 vertex block index
  38755. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38756. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38757. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38758. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38759. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38760. subSq = options.subDiv.max * options.subDiv.max;
  38761. options.facetPartitioning.length = 0;
  38762. }
  38763. // reset the normals
  38764. for (index = 0; index < positions.length; index++) {
  38765. normals[index] = 0.0;
  38766. }
  38767. // Loop : 1 indice triplet = 1 facet
  38768. var nbFaces = (indices.length / 3) | 0;
  38769. for (index = 0; index < nbFaces; index++) {
  38770. // get the indexes of the coordinates of each vertex of the facet
  38771. v1x = indices[index * 3] * 3;
  38772. v1y = v1x + 1;
  38773. v1z = v1x + 2;
  38774. v2x = indices[index * 3 + 1] * 3;
  38775. v2y = v2x + 1;
  38776. v2z = v2x + 2;
  38777. v3x = indices[index * 3 + 2] * 3;
  38778. v3y = v3x + 1;
  38779. v3z = v3x + 2;
  38780. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38781. p1p2y = positions[v1y] - positions[v2y];
  38782. p1p2z = positions[v1z] - positions[v2z];
  38783. p3p2x = positions[v3x] - positions[v2x];
  38784. p3p2y = positions[v3y] - positions[v2y];
  38785. p3p2z = positions[v3z] - positions[v2z];
  38786. // compute the face normal with the cross product
  38787. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38788. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38789. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38790. // normalize this normal and store it in the array facetData
  38791. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38792. length = (length === 0) ? 1.0 : length;
  38793. faceNormalx /= length;
  38794. faceNormaly /= length;
  38795. faceNormalz /= length;
  38796. if (computeFacetNormals && options) {
  38797. options.facetNormals[index].x = faceNormalx;
  38798. options.facetNormals[index].y = faceNormaly;
  38799. options.facetNormals[index].z = faceNormalz;
  38800. }
  38801. if (computeFacetPositions && options) {
  38802. // compute and the facet barycenter coordinates in the array facetPositions
  38803. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38804. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38805. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38806. }
  38807. if (computeFacetPartitioning && options) {
  38808. // store the facet indexes in arrays in the main facetPartitioning array :
  38809. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38810. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38811. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38812. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38813. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38814. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38815. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38816. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38817. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38818. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38819. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38820. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38821. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38822. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38823. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38824. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38825. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38826. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38827. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38828. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38829. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38830. // push each facet index in each block containing the vertex
  38831. options.facetPartitioning[block_idx_v1].push(index);
  38832. if (block_idx_v2 != block_idx_v1) {
  38833. options.facetPartitioning[block_idx_v2].push(index);
  38834. }
  38835. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38836. options.facetPartitioning[block_idx_v3].push(index);
  38837. }
  38838. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38839. options.facetPartitioning[block_idx_o].push(index);
  38840. }
  38841. }
  38842. if (computeDepthSort && options && options.facetPositions) {
  38843. var dsf = depthSortedFacets[index];
  38844. dsf.ind = index * 3;
  38845. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38846. }
  38847. // compute the normals anyway
  38848. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38849. normals[v1y] += faceNormaly;
  38850. normals[v1z] += faceNormalz;
  38851. normals[v2x] += faceNormalx;
  38852. normals[v2y] += faceNormaly;
  38853. normals[v2z] += faceNormalz;
  38854. normals[v3x] += faceNormalx;
  38855. normals[v3y] += faceNormaly;
  38856. normals[v3z] += faceNormalz;
  38857. }
  38858. // last normalization of each normal
  38859. for (index = 0; index < normals.length / 3; index++) {
  38860. faceNormalx = normals[index * 3];
  38861. faceNormaly = normals[index * 3 + 1];
  38862. faceNormalz = normals[index * 3 + 2];
  38863. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38864. length = (length === 0) ? 1.0 : length;
  38865. faceNormalx /= length;
  38866. faceNormaly /= length;
  38867. faceNormalz /= length;
  38868. normals[index * 3] = faceNormalx;
  38869. normals[index * 3 + 1] = faceNormaly;
  38870. normals[index * 3 + 2] = faceNormalz;
  38871. }
  38872. };
  38873. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38874. var li = indices.length;
  38875. var ln = normals.length;
  38876. var i;
  38877. var n;
  38878. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38879. switch (sideOrientation) {
  38880. case BABYLON.Mesh.FRONTSIDE:
  38881. // nothing changed
  38882. break;
  38883. case BABYLON.Mesh.BACKSIDE:
  38884. var tmp;
  38885. // indices
  38886. for (i = 0; i < li; i += 3) {
  38887. tmp = indices[i];
  38888. indices[i] = indices[i + 2];
  38889. indices[i + 2] = tmp;
  38890. }
  38891. // normals
  38892. for (n = 0; n < ln; n++) {
  38893. normals[n] = -normals[n];
  38894. }
  38895. break;
  38896. case BABYLON.Mesh.DOUBLESIDE:
  38897. // positions
  38898. var lp = positions.length;
  38899. var l = lp / 3;
  38900. for (var p = 0; p < lp; p++) {
  38901. positions[lp + p] = positions[p];
  38902. }
  38903. // indices
  38904. for (i = 0; i < li; i += 3) {
  38905. indices[i + li] = indices[i + 2] + l;
  38906. indices[i + 1 + li] = indices[i + 1] + l;
  38907. indices[i + 2 + li] = indices[i] + l;
  38908. }
  38909. // normals
  38910. for (n = 0; n < ln; n++) {
  38911. normals[ln + n] = -normals[n];
  38912. }
  38913. // uvs
  38914. var lu = uvs.length;
  38915. var u = 0;
  38916. for (u = 0; u < lu; u++) {
  38917. uvs[u + lu] = uvs[u];
  38918. }
  38919. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38920. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38921. u = 0;
  38922. for (i = 0; i < lu / 2; i++) {
  38923. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38924. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38925. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38926. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38927. u += 2;
  38928. }
  38929. break;
  38930. }
  38931. };
  38932. /**
  38933. * Applies VertexData created from the imported parameters to the geometry
  38934. * @param parsedVertexData the parsed data from an imported file
  38935. * @param geometry the geometry to apply the VertexData to
  38936. */
  38937. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38938. var vertexData = new VertexData();
  38939. // positions
  38940. var positions = parsedVertexData.positions;
  38941. if (positions) {
  38942. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38943. }
  38944. // normals
  38945. var normals = parsedVertexData.normals;
  38946. if (normals) {
  38947. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38948. }
  38949. // tangents
  38950. var tangents = parsedVertexData.tangents;
  38951. if (tangents) {
  38952. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38953. }
  38954. // uvs
  38955. var uvs = parsedVertexData.uvs;
  38956. if (uvs) {
  38957. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38958. }
  38959. // uv2s
  38960. var uv2s = parsedVertexData.uv2s;
  38961. if (uv2s) {
  38962. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38963. }
  38964. // uv3s
  38965. var uv3s = parsedVertexData.uv3s;
  38966. if (uv3s) {
  38967. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38968. }
  38969. // uv4s
  38970. var uv4s = parsedVertexData.uv4s;
  38971. if (uv4s) {
  38972. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38973. }
  38974. // uv5s
  38975. var uv5s = parsedVertexData.uv5s;
  38976. if (uv5s) {
  38977. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38978. }
  38979. // uv6s
  38980. var uv6s = parsedVertexData.uv6s;
  38981. if (uv6s) {
  38982. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38983. }
  38984. // colors
  38985. var colors = parsedVertexData.colors;
  38986. if (colors) {
  38987. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38988. }
  38989. // matricesIndices
  38990. var matricesIndices = parsedVertexData.matricesIndices;
  38991. if (matricesIndices) {
  38992. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38993. }
  38994. // matricesWeights
  38995. var matricesWeights = parsedVertexData.matricesWeights;
  38996. if (matricesWeights) {
  38997. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38998. }
  38999. // indices
  39000. var indices = parsedVertexData.indices;
  39001. if (indices) {
  39002. vertexData.indices = indices;
  39003. }
  39004. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39005. };
  39006. return VertexData;
  39007. }());
  39008. BABYLON.VertexData = VertexData;
  39009. })(BABYLON || (BABYLON = {}));
  39010. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39011. var BABYLON;
  39012. (function (BABYLON) {
  39013. /**
  39014. * Class used to store geometry data (vertex buffers + index buffer)
  39015. */
  39016. var Geometry = /** @class */ (function () {
  39017. /**
  39018. * Creates a new geometry
  39019. * @param id defines the unique ID
  39020. * @param scene defines the hosting scene
  39021. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39022. * @param updatable defines if geometry must be updatable (false by default)
  39023. * @param mesh defines the mesh that will be associated with the geometry
  39024. */
  39025. function Geometry(id, scene, vertexData, updatable, mesh) {
  39026. if (updatable === void 0) { updatable = false; }
  39027. if (mesh === void 0) { mesh = null; }
  39028. /**
  39029. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39030. */
  39031. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39032. this._totalVertices = 0;
  39033. this._isDisposed = false;
  39034. this._indexBufferIsUpdatable = false;
  39035. this.id = id;
  39036. this._engine = scene.getEngine();
  39037. this._meshes = [];
  39038. this._scene = scene;
  39039. //Init vertex buffer cache
  39040. this._vertexBuffers = {};
  39041. this._indices = [];
  39042. this._updatable = updatable;
  39043. // vertexData
  39044. if (vertexData) {
  39045. this.setAllVerticesData(vertexData, updatable);
  39046. }
  39047. else {
  39048. this._totalVertices = 0;
  39049. this._indices = [];
  39050. }
  39051. if (this._engine.getCaps().vertexArrayObject) {
  39052. this._vertexArrayObjects = {};
  39053. }
  39054. // applyToMesh
  39055. if (mesh) {
  39056. if (mesh.getClassName() === "LinesMesh") {
  39057. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39058. this._updateExtend();
  39059. }
  39060. this.applyToMesh(mesh);
  39061. mesh.computeWorldMatrix(true);
  39062. }
  39063. }
  39064. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39065. /**
  39066. * 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
  39067. */
  39068. get: function () {
  39069. return this._boundingBias;
  39070. },
  39071. /**
  39072. * 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
  39073. */
  39074. set: function (value) {
  39075. if (this._boundingBias && this._boundingBias.equals(value)) {
  39076. return;
  39077. }
  39078. this._boundingBias = value.clone();
  39079. this._updateBoundingInfo(true, null);
  39080. },
  39081. enumerable: true,
  39082. configurable: true
  39083. });
  39084. /**
  39085. * Static function used to attach a new empty geometry to a mesh
  39086. * @param mesh defines the mesh to attach the geometry to
  39087. * @returns the new {BABYLON.Geometry}
  39088. */
  39089. Geometry.CreateGeometryForMesh = function (mesh) {
  39090. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39091. geometry.applyToMesh(mesh);
  39092. return geometry;
  39093. };
  39094. Object.defineProperty(Geometry.prototype, "extend", {
  39095. /**
  39096. * Gets the current extend of the geometry
  39097. */
  39098. get: function () {
  39099. return this._extend;
  39100. },
  39101. enumerable: true,
  39102. configurable: true
  39103. });
  39104. /**
  39105. * Gets the hosting scene
  39106. * @returns the hosting {BABYLON.Scene}
  39107. */
  39108. Geometry.prototype.getScene = function () {
  39109. return this._scene;
  39110. };
  39111. /**
  39112. * Gets the hosting engine
  39113. * @returns the hosting {BABYLON.Engine}
  39114. */
  39115. Geometry.prototype.getEngine = function () {
  39116. return this._engine;
  39117. };
  39118. /**
  39119. * Defines if the geometry is ready to use
  39120. * @returns true if the geometry is ready to be used
  39121. */
  39122. Geometry.prototype.isReady = function () {
  39123. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39124. };
  39125. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39126. /**
  39127. * Gets a value indicating that the geometry should not be serialized
  39128. */
  39129. get: function () {
  39130. for (var index = 0; index < this._meshes.length; index++) {
  39131. if (!this._meshes[index].doNotSerialize) {
  39132. return false;
  39133. }
  39134. }
  39135. return true;
  39136. },
  39137. enumerable: true,
  39138. configurable: true
  39139. });
  39140. /** @hidden */
  39141. Geometry.prototype._rebuild = function () {
  39142. if (this._vertexArrayObjects) {
  39143. this._vertexArrayObjects = {};
  39144. }
  39145. // Index buffer
  39146. if (this._meshes.length !== 0 && this._indices) {
  39147. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39148. }
  39149. // Vertex buffers
  39150. for (var key in this._vertexBuffers) {
  39151. var vertexBuffer = this._vertexBuffers[key];
  39152. vertexBuffer._rebuild();
  39153. }
  39154. };
  39155. /**
  39156. * Affects all geometry data in one call
  39157. * @param vertexData defines the geometry data
  39158. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39159. */
  39160. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39161. vertexData.applyToGeometry(this, updatable);
  39162. this.notifyUpdate();
  39163. };
  39164. /**
  39165. * Set specific vertex data
  39166. * @param kind defines the data kind (Position, normal, etc...)
  39167. * @param data defines the vertex data to use
  39168. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39169. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39170. */
  39171. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39172. if (updatable === void 0) { updatable = false; }
  39173. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39174. this.setVerticesBuffer(buffer);
  39175. };
  39176. /**
  39177. * Removes a specific vertex data
  39178. * @param kind defines the data kind (Position, normal, etc...)
  39179. */
  39180. Geometry.prototype.removeVerticesData = function (kind) {
  39181. if (this._vertexBuffers[kind]) {
  39182. this._vertexBuffers[kind].dispose();
  39183. delete this._vertexBuffers[kind];
  39184. }
  39185. };
  39186. /**
  39187. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39188. * @param buffer defines the vertex buffer to use
  39189. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39190. */
  39191. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39192. if (totalVertices === void 0) { totalVertices = null; }
  39193. var kind = buffer.getKind();
  39194. if (this._vertexBuffers[kind]) {
  39195. this._vertexBuffers[kind].dispose();
  39196. }
  39197. this._vertexBuffers[kind] = buffer;
  39198. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39199. var data = buffer.getData();
  39200. if (totalVertices != null) {
  39201. this._totalVertices = totalVertices;
  39202. }
  39203. else {
  39204. if (data != null) {
  39205. this._totalVertices = data.length / (buffer.byteStride / 4);
  39206. }
  39207. }
  39208. this._updateExtend(data);
  39209. this._resetPointsArrayCache();
  39210. var meshes = this._meshes;
  39211. var numOfMeshes = meshes.length;
  39212. for (var index = 0; index < numOfMeshes; index++) {
  39213. var mesh = meshes[index];
  39214. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39215. mesh._createGlobalSubMesh(false);
  39216. mesh.computeWorldMatrix(true);
  39217. }
  39218. }
  39219. this.notifyUpdate(kind);
  39220. if (this._vertexArrayObjects) {
  39221. this._disposeVertexArrayObjects();
  39222. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39223. }
  39224. };
  39225. /**
  39226. * Update a specific vertex buffer
  39227. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39228. * It will do nothing if the buffer is not updatable
  39229. * @param kind defines the data kind (Position, normal, etc...)
  39230. * @param data defines the data to use
  39231. * @param offset defines the offset in the target buffer where to store the data
  39232. * @param useBytes set to true if the offset is in bytes
  39233. */
  39234. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39235. if (useBytes === void 0) { useBytes = false; }
  39236. var vertexBuffer = this.getVertexBuffer(kind);
  39237. if (!vertexBuffer) {
  39238. return;
  39239. }
  39240. vertexBuffer.updateDirectly(data, offset, useBytes);
  39241. this.notifyUpdate(kind);
  39242. };
  39243. /**
  39244. * Update a specific vertex buffer
  39245. * This function will create a new buffer if the current one is not updatable
  39246. * @param kind defines the data kind (Position, normal, etc...)
  39247. * @param data defines the data to use
  39248. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39249. */
  39250. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39251. if (updateExtends === void 0) { updateExtends = false; }
  39252. var vertexBuffer = this.getVertexBuffer(kind);
  39253. if (!vertexBuffer) {
  39254. return;
  39255. }
  39256. vertexBuffer.update(data);
  39257. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39258. this._updateBoundingInfo(updateExtends, data);
  39259. }
  39260. this.notifyUpdate(kind);
  39261. };
  39262. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39263. if (updateExtends) {
  39264. this._updateExtend(data);
  39265. }
  39266. var meshes = this._meshes;
  39267. var numOfMeshes = meshes.length;
  39268. this._resetPointsArrayCache();
  39269. for (var index = 0; index < numOfMeshes; index++) {
  39270. var mesh = meshes[index];
  39271. if (updateExtends) {
  39272. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39273. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39274. var subMesh = mesh.subMeshes[subIndex];
  39275. subMesh.refreshBoundingInfo();
  39276. }
  39277. }
  39278. }
  39279. };
  39280. /** @hidden */
  39281. Geometry.prototype._bind = function (effect, indexToBind) {
  39282. if (!effect) {
  39283. return;
  39284. }
  39285. if (indexToBind === undefined) {
  39286. indexToBind = this._indexBuffer;
  39287. }
  39288. var vbs = this.getVertexBuffers();
  39289. if (!vbs) {
  39290. return;
  39291. }
  39292. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39293. this._engine.bindBuffers(vbs, indexToBind, effect);
  39294. return;
  39295. }
  39296. // Using VAO
  39297. if (!this._vertexArrayObjects[effect.key]) {
  39298. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39299. }
  39300. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39301. };
  39302. /**
  39303. * Gets total number of vertices
  39304. * @returns the total number of vertices
  39305. */
  39306. Geometry.prototype.getTotalVertices = function () {
  39307. if (!this.isReady()) {
  39308. return 0;
  39309. }
  39310. return this._totalVertices;
  39311. };
  39312. /**
  39313. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39314. * @param kind defines the data kind (Position, normal, etc...)
  39315. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39316. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39317. * @returns a float array containing vertex data
  39318. */
  39319. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39320. var vertexBuffer = this.getVertexBuffer(kind);
  39321. if (!vertexBuffer) {
  39322. return null;
  39323. }
  39324. var data = vertexBuffer.getData();
  39325. if (!data) {
  39326. return null;
  39327. }
  39328. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39329. var count = this._totalVertices * vertexBuffer.getSize();
  39330. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39331. var copy_1 = new Array(count);
  39332. vertexBuffer.forEach(count, function (value, index) {
  39333. copy_1[index] = value;
  39334. });
  39335. return copy_1;
  39336. }
  39337. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39338. if (data instanceof Array) {
  39339. var offset = vertexBuffer.byteOffset / 4;
  39340. return BABYLON.Tools.Slice(data, offset, offset + count);
  39341. }
  39342. else if (data instanceof ArrayBuffer) {
  39343. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39344. }
  39345. else {
  39346. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39347. }
  39348. }
  39349. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39350. return BABYLON.Tools.Slice(data);
  39351. }
  39352. return data;
  39353. };
  39354. /**
  39355. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39356. * @param kind defines the data kind (Position, normal, etc...)
  39357. * @returns true if the vertex buffer with the specified kind is updatable
  39358. */
  39359. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39360. var vb = this._vertexBuffers[kind];
  39361. if (!vb) {
  39362. return false;
  39363. }
  39364. return vb.isUpdatable();
  39365. };
  39366. /**
  39367. * Gets a specific vertex buffer
  39368. * @param kind defines the data kind (Position, normal, etc...)
  39369. * @returns a {BABYLON.VertexBuffer}
  39370. */
  39371. Geometry.prototype.getVertexBuffer = function (kind) {
  39372. if (!this.isReady()) {
  39373. return null;
  39374. }
  39375. return this._vertexBuffers[kind];
  39376. };
  39377. /**
  39378. * Returns all vertex buffers
  39379. * @return an object holding all vertex buffers indexed by kind
  39380. */
  39381. Geometry.prototype.getVertexBuffers = function () {
  39382. if (!this.isReady()) {
  39383. return null;
  39384. }
  39385. return this._vertexBuffers;
  39386. };
  39387. /**
  39388. * Gets a boolean indicating if specific vertex buffer is present
  39389. * @param kind defines the data kind (Position, normal, etc...)
  39390. * @returns true if data is present
  39391. */
  39392. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39393. if (!this._vertexBuffers) {
  39394. if (this._delayInfo) {
  39395. return this._delayInfo.indexOf(kind) !== -1;
  39396. }
  39397. return false;
  39398. }
  39399. return this._vertexBuffers[kind] !== undefined;
  39400. };
  39401. /**
  39402. * Gets a list of all attached data kinds (Position, normal, etc...)
  39403. * @returns a list of string containing all kinds
  39404. */
  39405. Geometry.prototype.getVerticesDataKinds = function () {
  39406. var result = [];
  39407. var kind;
  39408. if (!this._vertexBuffers && this._delayInfo) {
  39409. for (kind in this._delayInfo) {
  39410. result.push(kind);
  39411. }
  39412. }
  39413. else {
  39414. for (kind in this._vertexBuffers) {
  39415. result.push(kind);
  39416. }
  39417. }
  39418. return result;
  39419. };
  39420. /**
  39421. * Update index buffer
  39422. * @param indices defines the indices to store in the index buffer
  39423. * @param offset defines the offset in the target buffer where to store the data
  39424. */
  39425. Geometry.prototype.updateIndices = function (indices, offset) {
  39426. if (!this._indexBuffer) {
  39427. return;
  39428. }
  39429. if (!this._indexBufferIsUpdatable) {
  39430. this.setIndices(indices, null, true);
  39431. }
  39432. else {
  39433. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39434. }
  39435. };
  39436. /**
  39437. * Creates a new index buffer
  39438. * @param indices defines the indices to store in the index buffer
  39439. * @param totalVertices defines the total number of vertices (could be null)
  39440. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39441. */
  39442. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39443. if (totalVertices === void 0) { totalVertices = null; }
  39444. if (updatable === void 0) { updatable = false; }
  39445. if (this._indexBuffer) {
  39446. this._engine._releaseBuffer(this._indexBuffer);
  39447. }
  39448. this._disposeVertexArrayObjects();
  39449. this._indices = indices;
  39450. this._indexBufferIsUpdatable = updatable;
  39451. if (this._meshes.length !== 0 && this._indices) {
  39452. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39453. }
  39454. if (totalVertices != undefined) { // including null and undefined
  39455. this._totalVertices = totalVertices;
  39456. }
  39457. var meshes = this._meshes;
  39458. var numOfMeshes = meshes.length;
  39459. for (var index = 0; index < numOfMeshes; index++) {
  39460. meshes[index]._createGlobalSubMesh(true);
  39461. }
  39462. this.notifyUpdate();
  39463. };
  39464. /**
  39465. * Return the total number of indices
  39466. * @returns the total number of indices
  39467. */
  39468. Geometry.prototype.getTotalIndices = function () {
  39469. if (!this.isReady()) {
  39470. return 0;
  39471. }
  39472. return this._indices.length;
  39473. };
  39474. /**
  39475. * Gets the index buffer array
  39476. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39477. * @returns the index buffer array
  39478. */
  39479. Geometry.prototype.getIndices = function (copyWhenShared) {
  39480. if (!this.isReady()) {
  39481. return null;
  39482. }
  39483. var orig = this._indices;
  39484. if (!copyWhenShared || this._meshes.length === 1) {
  39485. return orig;
  39486. }
  39487. else {
  39488. var len = orig.length;
  39489. var copy = [];
  39490. for (var i = 0; i < len; i++) {
  39491. copy.push(orig[i]);
  39492. }
  39493. return copy;
  39494. }
  39495. };
  39496. /**
  39497. * Gets the index buffer
  39498. * @return the index buffer
  39499. */
  39500. Geometry.prototype.getIndexBuffer = function () {
  39501. if (!this.isReady()) {
  39502. return null;
  39503. }
  39504. return this._indexBuffer;
  39505. };
  39506. /** @hidden */
  39507. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39508. if (effect === void 0) { effect = null; }
  39509. if (!effect || !this._vertexArrayObjects) {
  39510. return;
  39511. }
  39512. if (this._vertexArrayObjects[effect.key]) {
  39513. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39514. delete this._vertexArrayObjects[effect.key];
  39515. }
  39516. };
  39517. /**
  39518. * Release the associated resources for a specific mesh
  39519. * @param mesh defines the source mesh
  39520. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39521. */
  39522. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39523. var meshes = this._meshes;
  39524. var index = meshes.indexOf(mesh);
  39525. if (index === -1) {
  39526. return;
  39527. }
  39528. meshes.splice(index, 1);
  39529. mesh._geometry = null;
  39530. if (meshes.length === 0 && shouldDispose) {
  39531. this.dispose();
  39532. }
  39533. };
  39534. /**
  39535. * Apply current geometry to a given mesh
  39536. * @param mesh defines the mesh to apply geometry to
  39537. */
  39538. Geometry.prototype.applyToMesh = function (mesh) {
  39539. if (mesh._geometry === this) {
  39540. return;
  39541. }
  39542. var previousGeometry = mesh._geometry;
  39543. if (previousGeometry) {
  39544. previousGeometry.releaseForMesh(mesh);
  39545. }
  39546. var meshes = this._meshes;
  39547. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39548. mesh._geometry = this;
  39549. this._scene.pushGeometry(this);
  39550. meshes.push(mesh);
  39551. if (this.isReady()) {
  39552. this._applyToMesh(mesh);
  39553. }
  39554. else {
  39555. mesh._boundingInfo = this._boundingInfo;
  39556. }
  39557. };
  39558. Geometry.prototype._updateExtend = function (data) {
  39559. if (data === void 0) { data = null; }
  39560. if (!data) {
  39561. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39562. }
  39563. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39564. };
  39565. Geometry.prototype._applyToMesh = function (mesh) {
  39566. var numOfMeshes = this._meshes.length;
  39567. // vertexBuffers
  39568. for (var kind in this._vertexBuffers) {
  39569. if (numOfMeshes === 1) {
  39570. this._vertexBuffers[kind].create();
  39571. }
  39572. var buffer = this._vertexBuffers[kind].getBuffer();
  39573. if (buffer)
  39574. buffer.references = numOfMeshes;
  39575. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39576. if (!this._extend) {
  39577. this._updateExtend();
  39578. }
  39579. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39580. mesh._createGlobalSubMesh(false);
  39581. //bounding info was just created again, world matrix should be applied again.
  39582. mesh._updateBoundingInfo();
  39583. }
  39584. }
  39585. // indexBuffer
  39586. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39587. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39588. }
  39589. if (this._indexBuffer) {
  39590. this._indexBuffer.references = numOfMeshes;
  39591. }
  39592. };
  39593. Geometry.prototype.notifyUpdate = function (kind) {
  39594. if (this.onGeometryUpdated) {
  39595. this.onGeometryUpdated(this, kind);
  39596. }
  39597. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39598. var mesh = _a[_i];
  39599. mesh._markSubMeshesAsAttributesDirty();
  39600. }
  39601. };
  39602. /**
  39603. * Load the geometry if it was flagged as delay loaded
  39604. * @param scene defines the hosting scene
  39605. * @param onLoaded defines a callback called when the geometry is loaded
  39606. */
  39607. Geometry.prototype.load = function (scene, onLoaded) {
  39608. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39609. return;
  39610. }
  39611. if (this.isReady()) {
  39612. if (onLoaded) {
  39613. onLoaded();
  39614. }
  39615. return;
  39616. }
  39617. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39618. this._queueLoad(scene, onLoaded);
  39619. };
  39620. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39621. var _this = this;
  39622. if (!this.delayLoadingFile) {
  39623. return;
  39624. }
  39625. scene._addPendingData(this);
  39626. scene._loadFile(this.delayLoadingFile, function (data) {
  39627. if (!_this._delayLoadingFunction) {
  39628. return;
  39629. }
  39630. _this._delayLoadingFunction(JSON.parse(data), _this);
  39631. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39632. _this._delayInfo = [];
  39633. scene._removePendingData(_this);
  39634. var meshes = _this._meshes;
  39635. var numOfMeshes = meshes.length;
  39636. for (var index = 0; index < numOfMeshes; index++) {
  39637. _this._applyToMesh(meshes[index]);
  39638. }
  39639. if (onLoaded) {
  39640. onLoaded();
  39641. }
  39642. }, undefined, true);
  39643. };
  39644. /**
  39645. * Invert the geometry to move from a right handed system to a left handed one.
  39646. */
  39647. Geometry.prototype.toLeftHanded = function () {
  39648. // Flip faces
  39649. var tIndices = this.getIndices(false);
  39650. if (tIndices != null && tIndices.length > 0) {
  39651. for (var i = 0; i < tIndices.length; i += 3) {
  39652. var tTemp = tIndices[i + 0];
  39653. tIndices[i + 0] = tIndices[i + 2];
  39654. tIndices[i + 2] = tTemp;
  39655. }
  39656. this.setIndices(tIndices);
  39657. }
  39658. // Negate position.z
  39659. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39660. if (tPositions != null && tPositions.length > 0) {
  39661. for (var i = 0; i < tPositions.length; i += 3) {
  39662. tPositions[i + 2] = -tPositions[i + 2];
  39663. }
  39664. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39665. }
  39666. // Negate normal.z
  39667. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39668. if (tNormals != null && tNormals.length > 0) {
  39669. for (var i = 0; i < tNormals.length; i += 3) {
  39670. tNormals[i + 2] = -tNormals[i + 2];
  39671. }
  39672. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39673. }
  39674. };
  39675. // Cache
  39676. /** @hidden */
  39677. Geometry.prototype._resetPointsArrayCache = function () {
  39678. this._positions = null;
  39679. };
  39680. /** @hidden */
  39681. Geometry.prototype._generatePointsArray = function () {
  39682. if (this._positions)
  39683. return true;
  39684. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39685. if (!data || data.length === 0) {
  39686. return false;
  39687. }
  39688. this._positions = [];
  39689. for (var index = 0; index < data.length; index += 3) {
  39690. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39691. }
  39692. return true;
  39693. };
  39694. /**
  39695. * Gets a value indicating if the geometry is disposed
  39696. * @returns true if the geometry was disposed
  39697. */
  39698. Geometry.prototype.isDisposed = function () {
  39699. return this._isDisposed;
  39700. };
  39701. Geometry.prototype._disposeVertexArrayObjects = function () {
  39702. if (this._vertexArrayObjects) {
  39703. for (var kind in this._vertexArrayObjects) {
  39704. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39705. }
  39706. this._vertexArrayObjects = {};
  39707. }
  39708. };
  39709. /**
  39710. * Free all associated resources
  39711. */
  39712. Geometry.prototype.dispose = function () {
  39713. var meshes = this._meshes;
  39714. var numOfMeshes = meshes.length;
  39715. var index;
  39716. for (index = 0; index < numOfMeshes; index++) {
  39717. this.releaseForMesh(meshes[index]);
  39718. }
  39719. this._meshes = [];
  39720. this._disposeVertexArrayObjects();
  39721. for (var kind in this._vertexBuffers) {
  39722. this._vertexBuffers[kind].dispose();
  39723. }
  39724. this._vertexBuffers = {};
  39725. this._totalVertices = 0;
  39726. if (this._indexBuffer) {
  39727. this._engine._releaseBuffer(this._indexBuffer);
  39728. }
  39729. this._indexBuffer = null;
  39730. this._indices = [];
  39731. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39732. this.delayLoadingFile = null;
  39733. this._delayLoadingFunction = null;
  39734. this._delayInfo = [];
  39735. this._boundingInfo = null;
  39736. this._scene.removeGeometry(this);
  39737. this._isDisposed = true;
  39738. };
  39739. /**
  39740. * Clone the current geometry into a new geometry
  39741. * @param id defines the unique ID of the new geometry
  39742. * @returns a new geometry object
  39743. */
  39744. Geometry.prototype.copy = function (id) {
  39745. var vertexData = new BABYLON.VertexData();
  39746. vertexData.indices = [];
  39747. var indices = this.getIndices();
  39748. if (indices) {
  39749. for (var index = 0; index < indices.length; index++) {
  39750. vertexData.indices.push(indices[index]);
  39751. }
  39752. }
  39753. var updatable = false;
  39754. var stopChecking = false;
  39755. var kind;
  39756. for (kind in this._vertexBuffers) {
  39757. // using slice() to make a copy of the array and not just reference it
  39758. var data = this.getVerticesData(kind);
  39759. if (data instanceof Float32Array) {
  39760. vertexData.set(new Float32Array(data), kind);
  39761. }
  39762. else {
  39763. vertexData.set(data.slice(0), kind);
  39764. }
  39765. if (!stopChecking) {
  39766. var vb = this.getVertexBuffer(kind);
  39767. if (vb) {
  39768. updatable = vb.isUpdatable();
  39769. stopChecking = !updatable;
  39770. }
  39771. }
  39772. }
  39773. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39774. geometry.delayLoadState = this.delayLoadState;
  39775. geometry.delayLoadingFile = this.delayLoadingFile;
  39776. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39777. for (kind in this._delayInfo) {
  39778. geometry._delayInfo = geometry._delayInfo || [];
  39779. geometry._delayInfo.push(kind);
  39780. }
  39781. // Bounding info
  39782. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39783. return geometry;
  39784. };
  39785. /**
  39786. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39787. * @return a JSON representation of the current geometry data (without the vertices data)
  39788. */
  39789. Geometry.prototype.serialize = function () {
  39790. var serializationObject = {};
  39791. serializationObject.id = this.id;
  39792. serializationObject.updatable = this._updatable;
  39793. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39794. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39795. }
  39796. return serializationObject;
  39797. };
  39798. Geometry.prototype.toNumberArray = function (origin) {
  39799. if (Array.isArray(origin)) {
  39800. return origin;
  39801. }
  39802. else {
  39803. return Array.prototype.slice.call(origin);
  39804. }
  39805. };
  39806. /**
  39807. * Serialize all vertices data into a JSON oject
  39808. * @returns a JSON representation of the current geometry data
  39809. */
  39810. Geometry.prototype.serializeVerticeData = function () {
  39811. var serializationObject = this.serialize();
  39812. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39813. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39814. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39815. serializationObject.positions._updatable = true;
  39816. }
  39817. }
  39818. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39819. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39820. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39821. serializationObject.normals._updatable = true;
  39822. }
  39823. }
  39824. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39825. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39826. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39827. serializationObject.tangets._updatable = true;
  39828. }
  39829. }
  39830. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39831. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39832. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39833. serializationObject.uvs._updatable = true;
  39834. }
  39835. }
  39836. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39837. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39838. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39839. serializationObject.uv2s._updatable = true;
  39840. }
  39841. }
  39842. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39843. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39844. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39845. serializationObject.uv3s._updatable = true;
  39846. }
  39847. }
  39848. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39849. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39850. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39851. serializationObject.uv4s._updatable = true;
  39852. }
  39853. }
  39854. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39855. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39856. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39857. serializationObject.uv5s._updatable = true;
  39858. }
  39859. }
  39860. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39861. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39862. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39863. serializationObject.uv6s._updatable = true;
  39864. }
  39865. }
  39866. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39867. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39868. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39869. serializationObject.colors._updatable = true;
  39870. }
  39871. }
  39872. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39873. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39874. serializationObject.matricesIndices._isExpanded = true;
  39875. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39876. serializationObject.matricesIndices._updatable = true;
  39877. }
  39878. }
  39879. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39880. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39881. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39882. serializationObject.matricesWeights._updatable = true;
  39883. }
  39884. }
  39885. serializationObject.indices = this.toNumberArray(this.getIndices());
  39886. return serializationObject;
  39887. };
  39888. // Statics
  39889. /**
  39890. * Extracts a clone of a mesh geometry
  39891. * @param mesh defines the source mesh
  39892. * @param id defines the unique ID of the new geometry object
  39893. * @returns the new geometry object
  39894. */
  39895. Geometry.ExtractFromMesh = function (mesh, id) {
  39896. var geometry = mesh._geometry;
  39897. if (!geometry) {
  39898. return null;
  39899. }
  39900. return geometry.copy(id);
  39901. };
  39902. /**
  39903. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39904. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39905. * Be aware Math.random() could cause collisions, but:
  39906. * "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"
  39907. * @returns a string containing a new GUID
  39908. */
  39909. Geometry.RandomId = function () {
  39910. return BABYLON.Tools.RandomId();
  39911. };
  39912. /** @hidden */
  39913. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39914. var scene = mesh.getScene();
  39915. // Geometry
  39916. var geometryId = parsedGeometry.geometryId;
  39917. if (geometryId) {
  39918. var geometry = scene.getGeometryByID(geometryId);
  39919. if (geometry) {
  39920. geometry.applyToMesh(mesh);
  39921. }
  39922. }
  39923. else if (parsedGeometry instanceof ArrayBuffer) {
  39924. var binaryInfo = mesh._binaryInfo;
  39925. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39926. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39928. }
  39929. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39930. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39931. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39932. }
  39933. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39934. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39935. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39936. }
  39937. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39938. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39939. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39940. }
  39941. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39942. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39943. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39944. }
  39945. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39946. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39947. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39948. }
  39949. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39950. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39951. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39952. }
  39953. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39954. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39955. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39956. }
  39957. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39958. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39959. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39960. }
  39961. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39962. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39963. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39964. }
  39965. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39966. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39967. var floatIndices = [];
  39968. for (var i = 0; i < matricesIndicesData.length; i++) {
  39969. var index = matricesIndicesData[i];
  39970. floatIndices.push(index & 0x000000FF);
  39971. floatIndices.push((index & 0x0000FF00) >> 8);
  39972. floatIndices.push((index & 0x00FF0000) >> 16);
  39973. floatIndices.push(index >> 24);
  39974. }
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39976. }
  39977. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39978. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39979. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39980. }
  39981. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39982. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39983. mesh.setIndices(indicesData, null);
  39984. }
  39985. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39986. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39987. mesh.subMeshes = [];
  39988. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39989. var materialIndex = subMeshesData[(i * 5) + 0];
  39990. var verticesStart = subMeshesData[(i * 5) + 1];
  39991. var verticesCount = subMeshesData[(i * 5) + 2];
  39992. var indexStart = subMeshesData[(i * 5) + 3];
  39993. var indexCount = subMeshesData[(i * 5) + 4];
  39994. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39995. }
  39996. }
  39997. }
  39998. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39999. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40000. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40001. if (parsedGeometry.tangents) {
  40002. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40003. }
  40004. if (parsedGeometry.uvs) {
  40005. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40006. }
  40007. if (parsedGeometry.uvs2) {
  40008. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40009. }
  40010. if (parsedGeometry.uvs3) {
  40011. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40012. }
  40013. if (parsedGeometry.uvs4) {
  40014. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40015. }
  40016. if (parsedGeometry.uvs5) {
  40017. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40018. }
  40019. if (parsedGeometry.uvs6) {
  40020. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40021. }
  40022. if (parsedGeometry.colors) {
  40023. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40024. }
  40025. if (parsedGeometry.matricesIndices) {
  40026. if (!parsedGeometry.matricesIndices._isExpanded) {
  40027. var floatIndices = [];
  40028. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40029. var matricesIndex = parsedGeometry.matricesIndices[i];
  40030. floatIndices.push(matricesIndex & 0x000000FF);
  40031. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40032. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40033. floatIndices.push(matricesIndex >> 24);
  40034. }
  40035. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40036. }
  40037. else {
  40038. delete parsedGeometry.matricesIndices._isExpanded;
  40039. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40040. }
  40041. }
  40042. if (parsedGeometry.matricesIndicesExtra) {
  40043. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40044. var floatIndices = [];
  40045. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40046. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40047. floatIndices.push(matricesIndex & 0x000000FF);
  40048. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40049. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40050. floatIndices.push(matricesIndex >> 24);
  40051. }
  40052. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40053. }
  40054. else {
  40055. delete parsedGeometry.matricesIndices._isExpanded;
  40056. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40057. }
  40058. }
  40059. if (parsedGeometry.matricesWeights) {
  40060. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40061. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40062. }
  40063. if (parsedGeometry.matricesWeightsExtra) {
  40064. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40065. }
  40066. mesh.setIndices(parsedGeometry.indices, null);
  40067. }
  40068. // SubMeshes
  40069. if (parsedGeometry.subMeshes) {
  40070. mesh.subMeshes = [];
  40071. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40072. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40073. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40074. }
  40075. }
  40076. // Flat shading
  40077. if (mesh._shouldGenerateFlatShading) {
  40078. mesh.convertToFlatShadedMesh();
  40079. delete mesh._shouldGenerateFlatShading;
  40080. }
  40081. // Update
  40082. mesh.computeWorldMatrix(true);
  40083. // Octree
  40084. var sceneOctree = scene.selectionOctree;
  40085. if (sceneOctree !== undefined && sceneOctree !== null) {
  40086. sceneOctree.addMesh(mesh);
  40087. }
  40088. };
  40089. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40090. var epsilon = 1e-3;
  40091. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40092. return;
  40093. }
  40094. var noInfluenceBoneIndex = 0.0;
  40095. if (parsedGeometry.skeletonId > -1) {
  40096. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40097. if (!skeleton) {
  40098. return;
  40099. }
  40100. noInfluenceBoneIndex = skeleton.bones.length;
  40101. }
  40102. else {
  40103. return;
  40104. }
  40105. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40106. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40107. var matricesWeights = parsedGeometry.matricesWeights;
  40108. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40109. var influencers = parsedGeometry.numBoneInfluencer;
  40110. var size = matricesWeights.length;
  40111. for (var i = 0; i < size; i += 4) {
  40112. var weight = 0.0;
  40113. var firstZeroWeight = -1;
  40114. for (var j = 0; j < 4; j++) {
  40115. var w = matricesWeights[i + j];
  40116. weight += w;
  40117. if (w < epsilon && firstZeroWeight < 0) {
  40118. firstZeroWeight = j;
  40119. }
  40120. }
  40121. if (matricesWeightsExtra) {
  40122. for (var j = 0; j < 4; j++) {
  40123. var w = matricesWeightsExtra[i + j];
  40124. weight += w;
  40125. if (w < epsilon && firstZeroWeight < 0) {
  40126. firstZeroWeight = j + 4;
  40127. }
  40128. }
  40129. }
  40130. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40131. firstZeroWeight = influencers - 1;
  40132. }
  40133. if (weight > epsilon) {
  40134. var mweight = 1.0 / weight;
  40135. for (var j = 0; j < 4; j++) {
  40136. matricesWeights[i + j] *= mweight;
  40137. }
  40138. if (matricesWeightsExtra) {
  40139. for (var j = 0; j < 4; j++) {
  40140. matricesWeightsExtra[i + j] *= mweight;
  40141. }
  40142. }
  40143. }
  40144. else {
  40145. if (firstZeroWeight >= 4) {
  40146. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40147. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40148. }
  40149. else {
  40150. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40151. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40152. }
  40153. }
  40154. }
  40155. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40156. if (parsedGeometry.matricesWeightsExtra) {
  40157. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40158. }
  40159. };
  40160. /**
  40161. * Create a new geometry from persisted data (Using .babylon file format)
  40162. * @param parsedVertexData defines the persisted data
  40163. * @param scene defines the hosting scene
  40164. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40165. * @returns the new geometry object
  40166. */
  40167. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40168. if (scene.getGeometryByID(parsedVertexData.id)) {
  40169. return null; // null since geometry could be something else than a box...
  40170. }
  40171. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40172. if (BABYLON.Tags) {
  40173. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40174. }
  40175. if (parsedVertexData.delayLoadingFile) {
  40176. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40177. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40178. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40179. geometry._delayInfo = [];
  40180. if (parsedVertexData.hasUVs) {
  40181. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40182. }
  40183. if (parsedVertexData.hasUVs2) {
  40184. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40185. }
  40186. if (parsedVertexData.hasUVs3) {
  40187. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40188. }
  40189. if (parsedVertexData.hasUVs4) {
  40190. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40191. }
  40192. if (parsedVertexData.hasUVs5) {
  40193. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40194. }
  40195. if (parsedVertexData.hasUVs6) {
  40196. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40197. }
  40198. if (parsedVertexData.hasColors) {
  40199. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40200. }
  40201. if (parsedVertexData.hasMatricesIndices) {
  40202. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40203. }
  40204. if (parsedVertexData.hasMatricesWeights) {
  40205. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40206. }
  40207. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40208. }
  40209. else {
  40210. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40211. }
  40212. scene.pushGeometry(geometry, true);
  40213. return geometry;
  40214. };
  40215. return Geometry;
  40216. }());
  40217. BABYLON.Geometry = Geometry;
  40218. // Primitives
  40219. /// Abstract class
  40220. /**
  40221. * Abstract class used to provide common services for all typed geometries
  40222. * @hidden
  40223. */
  40224. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40225. __extends(_PrimitiveGeometry, _super);
  40226. /**
  40227. * Creates a new typed geometry
  40228. * @param id defines the unique ID of the geometry
  40229. * @param scene defines the hosting scene
  40230. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40231. * @param mesh defines the hosting mesh (can be null)
  40232. */
  40233. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40234. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40235. if (mesh === void 0) { mesh = null; }
  40236. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40237. _this._canBeRegenerated = _canBeRegenerated;
  40238. _this._beingRegenerated = true;
  40239. _this.regenerate();
  40240. _this._beingRegenerated = false;
  40241. return _this;
  40242. }
  40243. /**
  40244. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40245. * @returns true if the geometry can be regenerated
  40246. */
  40247. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40248. return this._canBeRegenerated;
  40249. };
  40250. /**
  40251. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40252. */
  40253. _PrimitiveGeometry.prototype.regenerate = function () {
  40254. if (!this._canBeRegenerated) {
  40255. return;
  40256. }
  40257. this._beingRegenerated = true;
  40258. this.setAllVerticesData(this._regenerateVertexData(), false);
  40259. this._beingRegenerated = false;
  40260. };
  40261. /**
  40262. * Clone the geometry
  40263. * @param id defines the unique ID of the new geometry
  40264. * @returns the new geometry
  40265. */
  40266. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40267. return _super.prototype.copy.call(this, id);
  40268. };
  40269. // overrides
  40270. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40271. if (!this._beingRegenerated) {
  40272. return;
  40273. }
  40274. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40275. };
  40276. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40277. if (!this._beingRegenerated) {
  40278. return;
  40279. }
  40280. _super.prototype.setVerticesData.call(this, kind, data, false);
  40281. };
  40282. // to override
  40283. /** @hidden */
  40284. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40285. throw new Error("Abstract method");
  40286. };
  40287. _PrimitiveGeometry.prototype.copy = function (id) {
  40288. throw new Error("Must be overriden in sub-classes.");
  40289. };
  40290. _PrimitiveGeometry.prototype.serialize = function () {
  40291. var serializationObject = _super.prototype.serialize.call(this);
  40292. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40293. return serializationObject;
  40294. };
  40295. return _PrimitiveGeometry;
  40296. }(Geometry));
  40297. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40298. /**
  40299. * Creates a ribbon geometry
  40300. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40301. */
  40302. var RibbonGeometry = /** @class */ (function (_super) {
  40303. __extends(RibbonGeometry, _super);
  40304. /**
  40305. * Creates a ribbon geometry
  40306. * @param id defines the unique ID of the geometry
  40307. * @param scene defines the hosting scene
  40308. * @param pathArray defines the array of paths to use
  40309. * @param closeArray defines if the last path and the first path must be joined
  40310. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40311. * @param offset defines the offset between points
  40312. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40313. * @param mesh defines the hosting mesh (can be null)
  40314. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40315. */
  40316. function RibbonGeometry(id, scene,
  40317. /**
  40318. * Defines the array of paths to use
  40319. */
  40320. pathArray,
  40321. /**
  40322. * Defines if the last and first points of each path in your pathArray must be joined
  40323. */
  40324. closeArray,
  40325. /**
  40326. * Defines if the last and first points of each path in your pathArray must be joined
  40327. */
  40328. closePath,
  40329. /**
  40330. * Defines the offset between points
  40331. */
  40332. offset, canBeRegenerated, mesh,
  40333. /**
  40334. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40335. */
  40336. side) {
  40337. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40338. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40339. _this.pathArray = pathArray;
  40340. _this.closeArray = closeArray;
  40341. _this.closePath = closePath;
  40342. _this.offset = offset;
  40343. _this.side = side;
  40344. return _this;
  40345. }
  40346. /** @hidden */
  40347. RibbonGeometry.prototype._regenerateVertexData = function () {
  40348. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40349. };
  40350. RibbonGeometry.prototype.copy = function (id) {
  40351. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40352. };
  40353. return RibbonGeometry;
  40354. }(_PrimitiveGeometry));
  40355. BABYLON.RibbonGeometry = RibbonGeometry;
  40356. /**
  40357. * Creates a box geometry
  40358. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40359. */
  40360. var BoxGeometry = /** @class */ (function (_super) {
  40361. __extends(BoxGeometry, _super);
  40362. /**
  40363. * Creates a box geometry
  40364. * @param id defines the unique ID of the geometry
  40365. * @param scene defines the hosting scene
  40366. * @param size defines the zise of the box (width, height and depth are the same)
  40367. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40368. * @param mesh defines the hosting mesh (can be null)
  40369. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40370. */
  40371. function BoxGeometry(id, scene,
  40372. /**
  40373. * Defines the zise of the box (width, height and depth are the same)
  40374. */
  40375. size, canBeRegenerated, mesh,
  40376. /**
  40377. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40378. */
  40379. side) {
  40380. if (mesh === void 0) { mesh = null; }
  40381. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40382. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40383. _this.size = size;
  40384. _this.side = side;
  40385. return _this;
  40386. }
  40387. BoxGeometry.prototype._regenerateVertexData = function () {
  40388. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40389. };
  40390. BoxGeometry.prototype.copy = function (id) {
  40391. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40392. };
  40393. BoxGeometry.prototype.serialize = function () {
  40394. var serializationObject = _super.prototype.serialize.call(this);
  40395. serializationObject.size = this.size;
  40396. return serializationObject;
  40397. };
  40398. BoxGeometry.Parse = function (parsedBox, scene) {
  40399. if (scene.getGeometryByID(parsedBox.id)) {
  40400. return null; // null since geometry could be something else than a box...
  40401. }
  40402. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40403. if (BABYLON.Tags) {
  40404. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40405. }
  40406. scene.pushGeometry(box, true);
  40407. return box;
  40408. };
  40409. return BoxGeometry;
  40410. }(_PrimitiveGeometry));
  40411. BABYLON.BoxGeometry = BoxGeometry;
  40412. /**
  40413. * Creates a sphere geometry
  40414. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40415. */
  40416. var SphereGeometry = /** @class */ (function (_super) {
  40417. __extends(SphereGeometry, _super);
  40418. /**
  40419. * Create a new sphere geometry
  40420. * @param id defines the unique ID of the geometry
  40421. * @param scene defines the hosting scene
  40422. * @param segments defines the number of segments to use to create the sphere
  40423. * @param diameter defines the diameter of the sphere
  40424. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40425. * @param mesh defines the hosting mesh (can be null)
  40426. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40427. */
  40428. function SphereGeometry(id, scene,
  40429. /**
  40430. * Defines the number of segments to use to create the sphere
  40431. */
  40432. segments,
  40433. /**
  40434. * Defines the diameter of the sphere
  40435. */
  40436. diameter, canBeRegenerated, mesh,
  40437. /**
  40438. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40439. */
  40440. side) {
  40441. if (mesh === void 0) { mesh = null; }
  40442. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40443. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40444. _this.segments = segments;
  40445. _this.diameter = diameter;
  40446. _this.side = side;
  40447. return _this;
  40448. }
  40449. SphereGeometry.prototype._regenerateVertexData = function () {
  40450. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40451. };
  40452. SphereGeometry.prototype.copy = function (id) {
  40453. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40454. };
  40455. SphereGeometry.prototype.serialize = function () {
  40456. var serializationObject = _super.prototype.serialize.call(this);
  40457. serializationObject.segments = this.segments;
  40458. serializationObject.diameter = this.diameter;
  40459. return serializationObject;
  40460. };
  40461. SphereGeometry.Parse = function (parsedSphere, scene) {
  40462. if (scene.getGeometryByID(parsedSphere.id)) {
  40463. return null; // null since geometry could be something else than a sphere...
  40464. }
  40465. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40466. if (BABYLON.Tags) {
  40467. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40468. }
  40469. scene.pushGeometry(sphere, true);
  40470. return sphere;
  40471. };
  40472. return SphereGeometry;
  40473. }(_PrimitiveGeometry));
  40474. BABYLON.SphereGeometry = SphereGeometry;
  40475. /**
  40476. * Creates a disc geometry
  40477. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40478. */
  40479. var DiscGeometry = /** @class */ (function (_super) {
  40480. __extends(DiscGeometry, _super);
  40481. /**
  40482. * Creates a new disc geometry
  40483. * @param id defines the unique ID of the geometry
  40484. * @param scene defines the hosting scene
  40485. * @param radius defines the radius of the disc
  40486. * @param tessellation defines the tesselation factor to apply to the disc
  40487. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40488. * @param mesh defines the hosting mesh (can be null)
  40489. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40490. */
  40491. function DiscGeometry(id, scene,
  40492. /**
  40493. * Defines the radius of the disc
  40494. */
  40495. radius,
  40496. /**
  40497. * Defines the tesselation factor to apply to the disc
  40498. */
  40499. tessellation, canBeRegenerated, mesh,
  40500. /**
  40501. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40502. */
  40503. side) {
  40504. if (mesh === void 0) { mesh = null; }
  40505. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40506. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40507. _this.radius = radius;
  40508. _this.tessellation = tessellation;
  40509. _this.side = side;
  40510. return _this;
  40511. }
  40512. DiscGeometry.prototype._regenerateVertexData = function () {
  40513. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40514. };
  40515. DiscGeometry.prototype.copy = function (id) {
  40516. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40517. };
  40518. return DiscGeometry;
  40519. }(_PrimitiveGeometry));
  40520. BABYLON.DiscGeometry = DiscGeometry;
  40521. /**
  40522. * Creates a new cylinder geometry
  40523. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40524. */
  40525. var CylinderGeometry = /** @class */ (function (_super) {
  40526. __extends(CylinderGeometry, _super);
  40527. /**
  40528. * Creates a new cylinder geometry
  40529. * @param id defines the unique ID of the geometry
  40530. * @param scene defines the hosting scene
  40531. * @param height defines the height of the cylinder
  40532. * @param diameterTop defines the diameter of the cylinder's top cap
  40533. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40534. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40535. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40536. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40537. * @param mesh defines the hosting mesh (can be null)
  40538. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40539. */
  40540. function CylinderGeometry(id, scene,
  40541. /**
  40542. * Defines the height of the cylinder
  40543. */
  40544. height,
  40545. /**
  40546. * Defines the diameter of the cylinder's top cap
  40547. */
  40548. diameterTop,
  40549. /**
  40550. * Defines the diameter of the cylinder's bottom cap
  40551. */
  40552. diameterBottom,
  40553. /**
  40554. * Defines the tessellation factor to apply to the cylinder
  40555. */
  40556. tessellation,
  40557. /**
  40558. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40559. */
  40560. subdivisions, canBeRegenerated, mesh,
  40561. /**
  40562. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40563. */
  40564. side) {
  40565. if (subdivisions === void 0) { subdivisions = 1; }
  40566. if (mesh === void 0) { mesh = null; }
  40567. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40568. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40569. _this.height = height;
  40570. _this.diameterTop = diameterTop;
  40571. _this.diameterBottom = diameterBottom;
  40572. _this.tessellation = tessellation;
  40573. _this.subdivisions = subdivisions;
  40574. _this.side = side;
  40575. return _this;
  40576. }
  40577. CylinderGeometry.prototype._regenerateVertexData = function () {
  40578. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40579. };
  40580. CylinderGeometry.prototype.copy = function (id) {
  40581. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40582. };
  40583. CylinderGeometry.prototype.serialize = function () {
  40584. var serializationObject = _super.prototype.serialize.call(this);
  40585. serializationObject.height = this.height;
  40586. serializationObject.diameterTop = this.diameterTop;
  40587. serializationObject.diameterBottom = this.diameterBottom;
  40588. serializationObject.tessellation = this.tessellation;
  40589. return serializationObject;
  40590. };
  40591. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40592. if (scene.getGeometryByID(parsedCylinder.id)) {
  40593. return null; // null since geometry could be something else than a cylinder...
  40594. }
  40595. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40596. if (BABYLON.Tags) {
  40597. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40598. }
  40599. scene.pushGeometry(cylinder, true);
  40600. return cylinder;
  40601. };
  40602. return CylinderGeometry;
  40603. }(_PrimitiveGeometry));
  40604. BABYLON.CylinderGeometry = CylinderGeometry;
  40605. /**
  40606. * Creates a new torus geometry
  40607. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40608. */
  40609. var TorusGeometry = /** @class */ (function (_super) {
  40610. __extends(TorusGeometry, _super);
  40611. /**
  40612. * Creates a new torus geometry
  40613. * @param id defines the unique ID of the geometry
  40614. * @param scene defines the hosting scene
  40615. * @param diameter defines the diameter of the torus
  40616. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40617. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40618. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40619. * @param mesh defines the hosting mesh (can be null)
  40620. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40621. */
  40622. function TorusGeometry(id, scene,
  40623. /**
  40624. * Defines the diameter of the torus
  40625. */
  40626. diameter,
  40627. /**
  40628. * Defines the thickness of the torus (ie. internal diameter)
  40629. */
  40630. thickness,
  40631. /**
  40632. * Defines the tesselation factor to apply to the torus
  40633. */
  40634. tessellation, canBeRegenerated, mesh,
  40635. /**
  40636. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40637. */
  40638. side) {
  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.diameter = diameter;
  40643. _this.thickness = thickness;
  40644. _this.tessellation = tessellation;
  40645. _this.side = side;
  40646. return _this;
  40647. }
  40648. TorusGeometry.prototype._regenerateVertexData = function () {
  40649. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40650. };
  40651. TorusGeometry.prototype.copy = function (id) {
  40652. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40653. };
  40654. TorusGeometry.prototype.serialize = function () {
  40655. var serializationObject = _super.prototype.serialize.call(this);
  40656. serializationObject.diameter = this.diameter;
  40657. serializationObject.thickness = this.thickness;
  40658. serializationObject.tessellation = this.tessellation;
  40659. return serializationObject;
  40660. };
  40661. TorusGeometry.Parse = function (parsedTorus, scene) {
  40662. if (scene.getGeometryByID(parsedTorus.id)) {
  40663. return null; // null since geometry could be something else than a torus...
  40664. }
  40665. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40666. if (BABYLON.Tags) {
  40667. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40668. }
  40669. scene.pushGeometry(torus, true);
  40670. return torus;
  40671. };
  40672. return TorusGeometry;
  40673. }(_PrimitiveGeometry));
  40674. BABYLON.TorusGeometry = TorusGeometry;
  40675. /**
  40676. * Creates a new ground geometry
  40677. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40678. */
  40679. var GroundGeometry = /** @class */ (function (_super) {
  40680. __extends(GroundGeometry, _super);
  40681. /**
  40682. * Creates a new ground geometry
  40683. * @param id defines the unique ID of the geometry
  40684. * @param scene defines the hosting scene
  40685. * @param width defines the width of the ground
  40686. * @param height defines the height of the ground
  40687. * @param subdivisions defines the subdivisions to apply to the ground
  40688. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40689. * @param mesh defines the hosting mesh (can be null)
  40690. */
  40691. function GroundGeometry(id, scene,
  40692. /**
  40693. * Defines the width of the ground
  40694. */
  40695. width,
  40696. /**
  40697. * Defines the height of the ground
  40698. */
  40699. height,
  40700. /**
  40701. * Defines the subdivisions to apply to the ground
  40702. */
  40703. subdivisions, canBeRegenerated, mesh) {
  40704. if (mesh === void 0) { mesh = null; }
  40705. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40706. _this.width = width;
  40707. _this.height = height;
  40708. _this.subdivisions = subdivisions;
  40709. return _this;
  40710. }
  40711. GroundGeometry.prototype._regenerateVertexData = function () {
  40712. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40713. };
  40714. GroundGeometry.prototype.copy = function (id) {
  40715. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40716. };
  40717. GroundGeometry.prototype.serialize = function () {
  40718. var serializationObject = _super.prototype.serialize.call(this);
  40719. serializationObject.width = this.width;
  40720. serializationObject.height = this.height;
  40721. serializationObject.subdivisions = this.subdivisions;
  40722. return serializationObject;
  40723. };
  40724. GroundGeometry.Parse = function (parsedGround, scene) {
  40725. if (scene.getGeometryByID(parsedGround.id)) {
  40726. return null; // null since geometry could be something else than a ground...
  40727. }
  40728. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40729. if (BABYLON.Tags) {
  40730. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40731. }
  40732. scene.pushGeometry(ground, true);
  40733. return ground;
  40734. };
  40735. return GroundGeometry;
  40736. }(_PrimitiveGeometry));
  40737. BABYLON.GroundGeometry = GroundGeometry;
  40738. /**
  40739. * Creates a tiled ground geometry
  40740. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40741. */
  40742. var TiledGroundGeometry = /** @class */ (function (_super) {
  40743. __extends(TiledGroundGeometry, _super);
  40744. /**
  40745. * Creates a tiled ground geometry
  40746. * @param id defines the unique ID of the geometry
  40747. * @param scene defines the hosting scene
  40748. * @param xmin defines the minimum value on X axis
  40749. * @param zmin defines the minimum value on Z axis
  40750. * @param xmax defines the maximum value on X axis
  40751. * @param zmax defines the maximum value on Z axis
  40752. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40753. * @param precision defines the precision to use when computing the tiles
  40754. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40755. * @param mesh defines the hosting mesh (can be null)
  40756. */
  40757. function TiledGroundGeometry(id, scene,
  40758. /**
  40759. * Defines the minimum value on X axis
  40760. */
  40761. xmin,
  40762. /**
  40763. * Defines the minimum value on Z axis
  40764. */
  40765. zmin,
  40766. /**
  40767. * Defines the maximum value on X axis
  40768. */
  40769. xmax,
  40770. /**
  40771. * Defines the maximum value on Z axis
  40772. */
  40773. zmax,
  40774. /**
  40775. * Defines the subdivisions to apply to the ground
  40776. */
  40777. subdivisions,
  40778. /**
  40779. * Defines the precision to use when computing the tiles
  40780. */
  40781. precision, canBeRegenerated, mesh) {
  40782. if (mesh === void 0) { mesh = null; }
  40783. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40784. _this.xmin = xmin;
  40785. _this.zmin = zmin;
  40786. _this.xmax = xmax;
  40787. _this.zmax = zmax;
  40788. _this.subdivisions = subdivisions;
  40789. _this.precision = precision;
  40790. return _this;
  40791. }
  40792. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40793. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40794. };
  40795. TiledGroundGeometry.prototype.copy = function (id) {
  40796. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40797. };
  40798. return TiledGroundGeometry;
  40799. }(_PrimitiveGeometry));
  40800. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40801. /**
  40802. * Creates a plane geometry
  40803. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40804. */
  40805. var PlaneGeometry = /** @class */ (function (_super) {
  40806. __extends(PlaneGeometry, _super);
  40807. /**
  40808. * Creates a plane geometry
  40809. * @param id defines the unique ID of the geometry
  40810. * @param scene defines the hosting scene
  40811. * @param size defines the size of the plane (width === height)
  40812. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40813. * @param mesh defines the hosting mesh (can be null)
  40814. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40815. */
  40816. function PlaneGeometry(id, scene,
  40817. /**
  40818. * Defines the size of the plane (width === height)
  40819. */
  40820. size, canBeRegenerated, mesh,
  40821. /**
  40822. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40823. */
  40824. side) {
  40825. if (mesh === void 0) { mesh = null; }
  40826. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40827. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40828. _this.size = size;
  40829. _this.side = side;
  40830. return _this;
  40831. }
  40832. PlaneGeometry.prototype._regenerateVertexData = function () {
  40833. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40834. };
  40835. PlaneGeometry.prototype.copy = function (id) {
  40836. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40837. };
  40838. PlaneGeometry.prototype.serialize = function () {
  40839. var serializationObject = _super.prototype.serialize.call(this);
  40840. serializationObject.size = this.size;
  40841. return serializationObject;
  40842. };
  40843. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40844. if (scene.getGeometryByID(parsedPlane.id)) {
  40845. return null; // null since geometry could be something else than a ground...
  40846. }
  40847. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40848. if (BABYLON.Tags) {
  40849. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40850. }
  40851. scene.pushGeometry(plane, true);
  40852. return plane;
  40853. };
  40854. return PlaneGeometry;
  40855. }(_PrimitiveGeometry));
  40856. BABYLON.PlaneGeometry = PlaneGeometry;
  40857. /**
  40858. * Creates a torus knot geometry
  40859. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40860. */
  40861. var TorusKnotGeometry = /** @class */ (function (_super) {
  40862. __extends(TorusKnotGeometry, _super);
  40863. /**
  40864. * Creates a torus knot geometry
  40865. * @param id defines the unique ID of the geometry
  40866. * @param scene defines the hosting scene
  40867. * @param radius defines the radius of the torus knot
  40868. * @param tube defines the thickness of the torus knot tube
  40869. * @param radialSegments defines the number of radial segments
  40870. * @param tubularSegments defines the number of tubular segments
  40871. * @param p defines the first number of windings
  40872. * @param q defines the second number of windings
  40873. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40874. * @param mesh defines the hosting mesh (can be null)
  40875. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40876. */
  40877. function TorusKnotGeometry(id, scene,
  40878. /**
  40879. * Defines the radius of the torus knot
  40880. */
  40881. radius,
  40882. /**
  40883. * Defines the thickness of the torus knot tube
  40884. */
  40885. tube,
  40886. /**
  40887. * Defines the number of radial segments
  40888. */
  40889. radialSegments,
  40890. /**
  40891. * Defines the number of tubular segments
  40892. */
  40893. tubularSegments,
  40894. /**
  40895. * Defines the first number of windings
  40896. */
  40897. p,
  40898. /**
  40899. * Defines the second number of windings
  40900. */
  40901. q, canBeRegenerated, mesh,
  40902. /**
  40903. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40904. */
  40905. side) {
  40906. if (mesh === void 0) { mesh = null; }
  40907. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40908. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40909. _this.radius = radius;
  40910. _this.tube = tube;
  40911. _this.radialSegments = radialSegments;
  40912. _this.tubularSegments = tubularSegments;
  40913. _this.p = p;
  40914. _this.q = q;
  40915. _this.side = side;
  40916. return _this;
  40917. }
  40918. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40919. 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 });
  40920. };
  40921. TorusKnotGeometry.prototype.copy = function (id) {
  40922. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40923. };
  40924. TorusKnotGeometry.prototype.serialize = function () {
  40925. var serializationObject = _super.prototype.serialize.call(this);
  40926. serializationObject.radius = this.radius;
  40927. serializationObject.tube = this.tube;
  40928. serializationObject.radialSegments = this.radialSegments;
  40929. serializationObject.tubularSegments = this.tubularSegments;
  40930. serializationObject.p = this.p;
  40931. serializationObject.q = this.q;
  40932. return serializationObject;
  40933. };
  40934. ;
  40935. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40936. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40937. return null; // null since geometry could be something else than a ground...
  40938. }
  40939. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40940. if (BABYLON.Tags) {
  40941. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40942. }
  40943. scene.pushGeometry(torusKnot, true);
  40944. return torusKnot;
  40945. };
  40946. return TorusKnotGeometry;
  40947. }(_PrimitiveGeometry));
  40948. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40949. //}
  40950. })(BABYLON || (BABYLON = {}));
  40951. //# sourceMappingURL=babylon.geometry.js.map
  40952. var BABYLON;
  40953. (function (BABYLON) {
  40954. /**
  40955. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40956. */
  40957. var PerformanceMonitor = /** @class */ (function () {
  40958. /**
  40959. * constructor
  40960. * @param frameSampleSize The number of samples required to saturate the sliding window
  40961. */
  40962. function PerformanceMonitor(frameSampleSize) {
  40963. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40964. this._enabled = true;
  40965. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40966. }
  40967. /**
  40968. * Samples current frame
  40969. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40970. */
  40971. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40972. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40973. if (!this._enabled)
  40974. return;
  40975. if (this._lastFrameTimeMs != null) {
  40976. var dt = timeMs - this._lastFrameTimeMs;
  40977. this._rollingFrameTime.add(dt);
  40978. }
  40979. this._lastFrameTimeMs = timeMs;
  40980. };
  40981. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40982. /**
  40983. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40984. * @return Average frame time in milliseconds
  40985. */
  40986. get: function () {
  40987. return this._rollingFrameTime.average;
  40988. },
  40989. enumerable: true,
  40990. configurable: true
  40991. });
  40992. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40993. /**
  40994. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40995. * @return Frame time variance in milliseconds squared
  40996. */
  40997. get: function () {
  40998. return this._rollingFrameTime.variance;
  40999. },
  41000. enumerable: true,
  41001. configurable: true
  41002. });
  41003. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41004. /**
  41005. * Returns the frame time of the most recent frame
  41006. * @return Frame time in milliseconds
  41007. */
  41008. get: function () {
  41009. return this._rollingFrameTime.history(0);
  41010. },
  41011. enumerable: true,
  41012. configurable: true
  41013. });
  41014. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41015. /**
  41016. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41017. * @return Framerate in frames per second
  41018. */
  41019. get: function () {
  41020. return 1000.0 / this._rollingFrameTime.average;
  41021. },
  41022. enumerable: true,
  41023. configurable: true
  41024. });
  41025. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41026. /**
  41027. * Returns the average framerate in frames per second using the most recent frame time
  41028. * @return Framerate in frames per second
  41029. */
  41030. get: function () {
  41031. var history = this._rollingFrameTime.history(0);
  41032. if (history === 0) {
  41033. return 0;
  41034. }
  41035. return 1000.0 / history;
  41036. },
  41037. enumerable: true,
  41038. configurable: true
  41039. });
  41040. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41041. /**
  41042. * Returns true if enough samples have been taken to completely fill the sliding window
  41043. * @return true if saturated
  41044. */
  41045. get: function () {
  41046. return this._rollingFrameTime.isSaturated();
  41047. },
  41048. enumerable: true,
  41049. configurable: true
  41050. });
  41051. /**
  41052. * Enables contributions to the sliding window sample set
  41053. */
  41054. PerformanceMonitor.prototype.enable = function () {
  41055. this._enabled = true;
  41056. };
  41057. /**
  41058. * Disables contributions to the sliding window sample set
  41059. * Samples will not be interpolated over the disabled period
  41060. */
  41061. PerformanceMonitor.prototype.disable = function () {
  41062. this._enabled = false;
  41063. //clear last sample to avoid interpolating over the disabled period when next enabled
  41064. this._lastFrameTimeMs = null;
  41065. };
  41066. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41067. /**
  41068. * Returns true if sampling is enabled
  41069. * @return true if enabled
  41070. */
  41071. get: function () {
  41072. return this._enabled;
  41073. },
  41074. enumerable: true,
  41075. configurable: true
  41076. });
  41077. /**
  41078. * Resets performance monitor
  41079. */
  41080. PerformanceMonitor.prototype.reset = function () {
  41081. //clear last sample to avoid interpolating over the disabled period when next enabled
  41082. this._lastFrameTimeMs = null;
  41083. //wipe record
  41084. this._rollingFrameTime.reset();
  41085. };
  41086. return PerformanceMonitor;
  41087. }());
  41088. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41089. /**
  41090. * RollingAverage
  41091. *
  41092. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41093. */
  41094. var RollingAverage = /** @class */ (function () {
  41095. /**
  41096. * constructor
  41097. * @param length The number of samples required to saturate the sliding window
  41098. */
  41099. function RollingAverage(length) {
  41100. this._samples = new Array(length);
  41101. this.reset();
  41102. }
  41103. /**
  41104. * Adds a sample to the sample set
  41105. * @param v The sample value
  41106. */
  41107. RollingAverage.prototype.add = function (v) {
  41108. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41109. var delta;
  41110. //we need to check if we've already wrapped round
  41111. if (this.isSaturated()) {
  41112. //remove bottom of stack from mean
  41113. var bottomValue = this._samples[this._pos];
  41114. delta = bottomValue - this.average;
  41115. this.average -= delta / (this._sampleCount - 1);
  41116. this._m2 -= delta * (bottomValue - this.average);
  41117. }
  41118. else {
  41119. this._sampleCount++;
  41120. }
  41121. //add new value to mean
  41122. delta = v - this.average;
  41123. this.average += delta / (this._sampleCount);
  41124. this._m2 += delta * (v - this.average);
  41125. //set the new variance
  41126. this.variance = this._m2 / (this._sampleCount - 1);
  41127. this._samples[this._pos] = v;
  41128. this._pos++;
  41129. this._pos %= this._samples.length; //positive wrap around
  41130. };
  41131. /**
  41132. * Returns previously added values or null if outside of history or outside the sliding window domain
  41133. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41134. * @return Value previously recorded with add() or null if outside of range
  41135. */
  41136. RollingAverage.prototype.history = function (i) {
  41137. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41138. return 0;
  41139. }
  41140. var i0 = this._wrapPosition(this._pos - 1.0);
  41141. return this._samples[this._wrapPosition(i0 - i)];
  41142. };
  41143. /**
  41144. * Returns true if enough samples have been taken to completely fill the sliding window
  41145. * @return true if sample-set saturated
  41146. */
  41147. RollingAverage.prototype.isSaturated = function () {
  41148. return this._sampleCount >= this._samples.length;
  41149. };
  41150. /**
  41151. * Resets the rolling average (equivalent to 0 samples taken so far)
  41152. */
  41153. RollingAverage.prototype.reset = function () {
  41154. this.average = 0;
  41155. this.variance = 0;
  41156. this._sampleCount = 0;
  41157. this._pos = 0;
  41158. this._m2 = 0;
  41159. };
  41160. /**
  41161. * Wraps a value around the sample range boundaries
  41162. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41163. * @return Wrapped position in sample range
  41164. */
  41165. RollingAverage.prototype._wrapPosition = function (i) {
  41166. var max = this._samples.length;
  41167. return ((i % max) + max) % max;
  41168. };
  41169. return RollingAverage;
  41170. }());
  41171. BABYLON.RollingAverage = RollingAverage;
  41172. })(BABYLON || (BABYLON = {}));
  41173. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41174. var BABYLON;
  41175. (function (BABYLON) {
  41176. /**
  41177. * "Static Class" containing the most commonly used helper while dealing with material for
  41178. * rendering purpose.
  41179. *
  41180. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41181. *
  41182. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41183. */
  41184. var MaterialHelper = /** @class */ (function () {
  41185. function MaterialHelper() {
  41186. }
  41187. /**
  41188. * Bind the current view position to an effect.
  41189. * @param effect The effect to be bound
  41190. * @param scene The scene the eyes position is used from
  41191. */
  41192. MaterialHelper.BindEyePosition = function (effect, scene) {
  41193. if (scene._forcedViewPosition) {
  41194. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41195. return;
  41196. }
  41197. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41198. };
  41199. /**
  41200. * Helps preparing the defines values about the UVs in used in the effect.
  41201. * UVs are shared as much as we can accross chanels in the shaders.
  41202. * @param texture The texture we are preparing the UVs for
  41203. * @param defines The defines to update
  41204. * @param key The chanel key "diffuse", "specular"... used in the shader
  41205. */
  41206. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41207. defines._needUVs = true;
  41208. defines[key] = true;
  41209. if (texture.getTextureMatrix().isIdentity(true)) {
  41210. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41211. if (texture.coordinatesIndex === 0) {
  41212. defines["MAINUV1"] = true;
  41213. }
  41214. else {
  41215. defines["MAINUV2"] = true;
  41216. }
  41217. }
  41218. else {
  41219. defines[key + "DIRECTUV"] = 0;
  41220. }
  41221. };
  41222. /**
  41223. * Binds a texture matrix value to its corrsponding uniform
  41224. * @param texture The texture to bind the matrix for
  41225. * @param uniformBuffer The uniform buffer receivin the data
  41226. * @param key The chanel key "diffuse", "specular"... used in the shader
  41227. */
  41228. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41229. var matrix = texture.getTextureMatrix();
  41230. if (!matrix.isIdentity(true)) {
  41231. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41232. }
  41233. };
  41234. /**
  41235. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41236. * @param mesh defines the current mesh
  41237. * @param scene defines the current scene
  41238. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41239. * @param pointsCloud defines if point cloud rendering has to be turned on
  41240. * @param fogEnabled defines if fog has to be turned on
  41241. * @param alphaTest defines if alpha testing has to be turned on
  41242. * @param defines defines the current list of defines
  41243. */
  41244. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41245. if (defines._areMiscDirty) {
  41246. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41247. defines["POINTSIZE"] = pointsCloud;
  41248. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41249. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41250. defines["ALPHATEST"] = alphaTest;
  41251. }
  41252. };
  41253. /**
  41254. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41255. * @param scene defines the current scene
  41256. * @param engine defines the current engine
  41257. * @param defines specifies the list of active defines
  41258. * @param useInstances defines if instances have to be turned on
  41259. * @param useClipPlane defines if clip plane have to be turned on
  41260. */
  41261. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41262. if (useClipPlane === void 0) { useClipPlane = null; }
  41263. var changed = false;
  41264. if (useClipPlane == null) {
  41265. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41266. }
  41267. if (defines["CLIPPLANE"] !== useClipPlane) {
  41268. defines["CLIPPLANE"] = useClipPlane;
  41269. changed = true;
  41270. }
  41271. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41272. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41273. changed = true;
  41274. }
  41275. if (defines["INSTANCES"] !== useInstances) {
  41276. defines["INSTANCES"] = useInstances;
  41277. changed = true;
  41278. }
  41279. if (changed) {
  41280. defines.markAsUnprocessed();
  41281. }
  41282. };
  41283. /**
  41284. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41285. * @param mesh The mesh containing the geometry data we will draw
  41286. * @param defines The defines to update
  41287. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41288. * @param useBones Precise whether bones should be used or not (override mesh info)
  41289. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41290. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41291. * @returns false if defines are considered not dirty and have not been checked
  41292. */
  41293. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41294. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41295. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41296. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41297. return false;
  41298. }
  41299. defines._normals = defines._needNormals;
  41300. defines._uvs = defines._needUVs;
  41301. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41302. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41303. defines["TANGENT"] = true;
  41304. }
  41305. if (defines._needUVs) {
  41306. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41307. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41308. }
  41309. else {
  41310. defines["UV1"] = false;
  41311. defines["UV2"] = false;
  41312. }
  41313. if (useVertexColor) {
  41314. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41315. defines["VERTEXCOLOR"] = hasVertexColors;
  41316. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41317. }
  41318. if (useBones) {
  41319. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41320. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41321. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41322. }
  41323. else {
  41324. defines["NUM_BONE_INFLUENCERS"] = 0;
  41325. defines["BonesPerMesh"] = 0;
  41326. }
  41327. }
  41328. if (useMorphTargets) {
  41329. var manager = mesh.morphTargetManager;
  41330. if (manager) {
  41331. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41332. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41333. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41334. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41335. }
  41336. else {
  41337. defines["MORPHTARGETS_TANGENT"] = false;
  41338. defines["MORPHTARGETS_NORMAL"] = false;
  41339. defines["MORPHTARGETS"] = false;
  41340. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41341. }
  41342. }
  41343. return true;
  41344. };
  41345. /**
  41346. * Prepares the defines related to the light information passed in parameter
  41347. * @param scene The scene we are intending to draw
  41348. * @param mesh The mesh the effect is compiling for
  41349. * @param defines The defines to update
  41350. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41351. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41352. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41353. * @returns true if normals will be required for the rest of the effect
  41354. */
  41355. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41356. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41357. if (disableLighting === void 0) { disableLighting = false; }
  41358. if (!defines._areLightsDirty) {
  41359. return defines._needNormals;
  41360. }
  41361. var lightIndex = 0;
  41362. var needNormals = false;
  41363. var needRebuild = false;
  41364. var lightmapMode = false;
  41365. var shadowEnabled = false;
  41366. var specularEnabled = false;
  41367. if (scene.lightsEnabled && !disableLighting) {
  41368. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41369. var light = _a[_i];
  41370. needNormals = true;
  41371. if (defines["LIGHT" + lightIndex] === undefined) {
  41372. needRebuild = true;
  41373. }
  41374. defines["LIGHT" + lightIndex] = true;
  41375. defines["SPOTLIGHT" + lightIndex] = false;
  41376. defines["HEMILIGHT" + lightIndex] = false;
  41377. defines["POINTLIGHT" + lightIndex] = false;
  41378. defines["DIRLIGHT" + lightIndex] = false;
  41379. var type;
  41380. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41381. type = "SPOTLIGHT" + lightIndex;
  41382. var spotLight = light;
  41383. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41384. }
  41385. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41386. type = "HEMILIGHT" + lightIndex;
  41387. }
  41388. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41389. type = "POINTLIGHT" + lightIndex;
  41390. }
  41391. else {
  41392. type = "DIRLIGHT" + lightIndex;
  41393. }
  41394. defines[type] = true;
  41395. // Specular
  41396. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41397. specularEnabled = true;
  41398. }
  41399. // Shadows
  41400. defines["SHADOW" + lightIndex] = false;
  41401. defines["SHADOWPCF" + lightIndex] = false;
  41402. defines["SHADOWPCSS" + lightIndex] = false;
  41403. defines["SHADOWPOISSON" + lightIndex] = false;
  41404. defines["SHADOWESM" + lightIndex] = false;
  41405. defines["SHADOWCUBE" + lightIndex] = false;
  41406. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41407. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41408. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41409. var shadowGenerator = light.getShadowGenerator();
  41410. if (shadowGenerator) {
  41411. shadowEnabled = true;
  41412. shadowGenerator.prepareDefines(defines, lightIndex);
  41413. }
  41414. }
  41415. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41416. lightmapMode = true;
  41417. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41418. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41419. }
  41420. else {
  41421. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41422. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41423. }
  41424. lightIndex++;
  41425. if (lightIndex === maxSimultaneousLights)
  41426. break;
  41427. }
  41428. }
  41429. defines["SPECULARTERM"] = specularEnabled;
  41430. defines["SHADOWS"] = shadowEnabled;
  41431. // Resetting all other lights if any
  41432. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41433. if (defines["LIGHT" + index] !== undefined) {
  41434. defines["LIGHT" + index] = false;
  41435. defines["HEMILIGHT" + lightIndex] = false;
  41436. defines["POINTLIGHT" + lightIndex] = false;
  41437. defines["DIRLIGHT" + lightIndex] = false;
  41438. defines["SPOTLIGHT" + lightIndex] = false;
  41439. defines["SHADOW" + lightIndex] = false;
  41440. }
  41441. }
  41442. var caps = scene.getEngine().getCaps();
  41443. if (defines["SHADOWFLOAT"] === undefined) {
  41444. needRebuild = true;
  41445. }
  41446. defines["SHADOWFLOAT"] = shadowEnabled &&
  41447. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41448. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41449. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41450. if (needRebuild) {
  41451. defines.rebuild();
  41452. }
  41453. return needNormals;
  41454. };
  41455. /**
  41456. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41457. * that won t be acctive due to defines being turned off.
  41458. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41459. * @param samplersList The samplers list
  41460. * @param defines The defines helping in the list generation
  41461. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41462. */
  41463. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41464. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41465. var uniformsList;
  41466. var uniformBuffersList = null;
  41467. if (uniformsListOrOptions.uniformsNames) {
  41468. var options = uniformsListOrOptions;
  41469. uniformsList = options.uniformsNames;
  41470. uniformBuffersList = options.uniformBuffersNames;
  41471. samplersList = options.samplers;
  41472. defines = options.defines;
  41473. maxSimultaneousLights = options.maxSimultaneousLights;
  41474. }
  41475. else {
  41476. uniformsList = uniformsListOrOptions;
  41477. if (!samplersList) {
  41478. samplersList = [];
  41479. }
  41480. }
  41481. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41482. if (!defines["LIGHT" + lightIndex]) {
  41483. break;
  41484. }
  41485. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41486. if (uniformBuffersList) {
  41487. uniformBuffersList.push("Light" + lightIndex);
  41488. }
  41489. samplersList.push("shadowSampler" + lightIndex);
  41490. samplersList.push("depthSampler" + lightIndex);
  41491. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41492. samplersList.push("projectionLightSampler" + lightIndex);
  41493. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41494. }
  41495. }
  41496. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41497. uniformsList.push("morphTargetInfluences");
  41498. }
  41499. };
  41500. /**
  41501. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41502. * @param defines The defines to update while falling back
  41503. * @param fallbacks The authorized effect fallbacks
  41504. * @param maxSimultaneousLights The maximum number of lights allowed
  41505. * @param rank the current rank of the Effect
  41506. * @returns The newly affected rank
  41507. */
  41508. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41509. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41510. if (rank === void 0) { rank = 0; }
  41511. var lightFallbackRank = 0;
  41512. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41513. if (!defines["LIGHT" + lightIndex]) {
  41514. break;
  41515. }
  41516. if (lightIndex > 0) {
  41517. lightFallbackRank = rank + lightIndex;
  41518. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41519. }
  41520. if (!defines["SHADOWS"]) {
  41521. if (defines["SHADOW" + lightIndex]) {
  41522. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41523. }
  41524. if (defines["SHADOWPCF" + lightIndex]) {
  41525. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41526. }
  41527. if (defines["SHADOWPCSS" + lightIndex]) {
  41528. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41529. }
  41530. if (defines["SHADOWPOISSON" + lightIndex]) {
  41531. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41532. }
  41533. if (defines["SHADOWESM" + lightIndex]) {
  41534. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41535. }
  41536. }
  41537. }
  41538. return lightFallbackRank++;
  41539. };
  41540. /**
  41541. * Prepares the list of attributes required for morph targets according to the effect defines.
  41542. * @param attribs The current list of supported attribs
  41543. * @param mesh The mesh to prepare the morph targets attributes for
  41544. * @param defines The current Defines of the effect
  41545. */
  41546. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41547. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41548. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41549. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41550. var manager = mesh.morphTargetManager;
  41551. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41552. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41553. for (var index = 0; index < influencers; index++) {
  41554. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41555. if (normal) {
  41556. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41557. }
  41558. if (tangent) {
  41559. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41560. }
  41561. if (attribs.length > maxAttributesCount) {
  41562. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41563. }
  41564. }
  41565. }
  41566. };
  41567. /**
  41568. * Prepares the list of attributes required for bones according to the effect defines.
  41569. * @param attribs The current list of supported attribs
  41570. * @param mesh The mesh to prepare the bones attributes for
  41571. * @param defines The current Defines of the effect
  41572. * @param fallbacks The current efffect fallback strategy
  41573. */
  41574. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41575. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41576. fallbacks.addCPUSkinningFallback(0, mesh);
  41577. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41578. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41579. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41580. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41581. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41582. }
  41583. }
  41584. };
  41585. /**
  41586. * Prepares the list of attributes required for instances according to the effect defines.
  41587. * @param attribs The current list of supported attribs
  41588. * @param defines The current Defines of the effect
  41589. */
  41590. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41591. if (defines["INSTANCES"]) {
  41592. attribs.push("world0");
  41593. attribs.push("world1");
  41594. attribs.push("world2");
  41595. attribs.push("world3");
  41596. }
  41597. };
  41598. /**
  41599. * Binds the light shadow information to the effect for the given mesh.
  41600. * @param light The light containing the generator
  41601. * @param scene The scene the lights belongs to
  41602. * @param mesh The mesh we are binding the information to render
  41603. * @param lightIndex The light index in the effect used to render the mesh
  41604. * @param effect The effect we are binding the data to
  41605. */
  41606. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41607. if (light.shadowEnabled && mesh.receiveShadows) {
  41608. var shadowGenerator = light.getShadowGenerator();
  41609. if (shadowGenerator) {
  41610. shadowGenerator.bindShadowLight(lightIndex, effect);
  41611. }
  41612. }
  41613. };
  41614. /**
  41615. * Binds the light information to the effect.
  41616. * @param light The light containing the generator
  41617. * @param effect The effect we are binding the data to
  41618. * @param lightIndex The light index in the effect used to render
  41619. */
  41620. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41621. light.transferToEffect(effect, lightIndex + "");
  41622. };
  41623. /**
  41624. * Binds the lights information from the scene to the effect for the given mesh.
  41625. * @param scene The scene the lights belongs to
  41626. * @param mesh The mesh we are binding the information to render
  41627. * @param effect The effect we are binding the data to
  41628. * @param defines The generated defines for the effect
  41629. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41630. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41631. */
  41632. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41633. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41634. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41635. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41636. for (var i = 0; i < len; i++) {
  41637. var light = mesh._lightSources[i];
  41638. var iAsString = i.toString();
  41639. var scaledIntensity = light.getScaledIntensity();
  41640. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41641. MaterialHelper.BindLightProperties(light, effect, i);
  41642. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41643. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41644. if (defines["SPECULARTERM"]) {
  41645. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41646. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41647. }
  41648. // Shadows
  41649. if (scene.shadowsEnabled) {
  41650. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41651. }
  41652. light._uniformBuffer.update();
  41653. }
  41654. };
  41655. /**
  41656. * Binds the fog information from the scene to the effect for the given mesh.
  41657. * @param scene The scene the lights belongs to
  41658. * @param mesh The mesh we are binding the information to render
  41659. * @param effect The effect we are binding the data to
  41660. */
  41661. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41662. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41663. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41664. effect.setColor3("vFogColor", scene.fogColor);
  41665. }
  41666. };
  41667. /**
  41668. * Binds the bones information from the mesh to the effect.
  41669. * @param mesh The mesh we are binding the information to render
  41670. * @param effect The effect we are binding the data to
  41671. */
  41672. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41673. if (!effect || !mesh) {
  41674. return;
  41675. }
  41676. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41677. mesh.computeBonesUsingShaders = false;
  41678. }
  41679. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41680. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41681. if (matrices) {
  41682. effect.setMatrices("mBones", matrices);
  41683. }
  41684. }
  41685. };
  41686. /**
  41687. * Binds the morph targets information from the mesh to the effect.
  41688. * @param abstractMesh The mesh we are binding the information to render
  41689. * @param effect The effect we are binding the data to
  41690. */
  41691. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41692. var manager = abstractMesh.morphTargetManager;
  41693. if (!abstractMesh || !manager) {
  41694. return;
  41695. }
  41696. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41697. };
  41698. /**
  41699. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41700. * @param defines The generated defines used in the effect
  41701. * @param effect The effect we are binding the data to
  41702. * @param scene The scene we are willing to render with logarithmic scale for
  41703. */
  41704. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41705. if (defines["LOGARITHMICDEPTH"]) {
  41706. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41707. }
  41708. };
  41709. /**
  41710. * Binds the clip plane information from the scene to the effect.
  41711. * @param scene The scene the clip plane information are extracted from
  41712. * @param effect The effect we are binding the data to
  41713. */
  41714. MaterialHelper.BindClipPlane = function (effect, scene) {
  41715. if (scene.clipPlane) {
  41716. var clipPlane = scene.clipPlane;
  41717. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41718. }
  41719. };
  41720. return MaterialHelper;
  41721. }());
  41722. BABYLON.MaterialHelper = MaterialHelper;
  41723. })(BABYLON || (BABYLON = {}));
  41724. //# sourceMappingURL=babylon.materialHelper.js.map
  41725. var BABYLON;
  41726. (function (BABYLON) {
  41727. var PushMaterial = /** @class */ (function (_super) {
  41728. __extends(PushMaterial, _super);
  41729. function PushMaterial(name, scene) {
  41730. var _this = _super.call(this, name, scene) || this;
  41731. _this._normalMatrix = new BABYLON.Matrix();
  41732. _this.storeEffectOnSubMeshes = true;
  41733. return _this;
  41734. }
  41735. PushMaterial.prototype.getEffect = function () {
  41736. return this._activeEffect;
  41737. };
  41738. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41739. if (!mesh) {
  41740. return false;
  41741. }
  41742. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41743. return true;
  41744. }
  41745. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41746. };
  41747. /**
  41748. * Binds the given world matrix to the active effect
  41749. *
  41750. * @param world the matrix to bind
  41751. */
  41752. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41753. this._activeEffect.setMatrix("world", world);
  41754. };
  41755. /**
  41756. * Binds the given normal matrix to the active effect
  41757. *
  41758. * @param normalMatrix the matrix to bind
  41759. */
  41760. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41761. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41762. };
  41763. PushMaterial.prototype.bind = function (world, mesh) {
  41764. if (!mesh) {
  41765. return;
  41766. }
  41767. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41768. };
  41769. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41770. if (effect === void 0) { effect = null; }
  41771. _super.prototype._afterBind.call(this, mesh);
  41772. this.getScene()._cachedEffect = effect;
  41773. };
  41774. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41775. if (visibility === void 0) { visibility = 1; }
  41776. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41777. };
  41778. return PushMaterial;
  41779. }(BABYLON.Material));
  41780. BABYLON.PushMaterial = PushMaterial;
  41781. })(BABYLON || (BABYLON = {}));
  41782. //# sourceMappingURL=babylon.pushMaterial.js.map
  41783. var BABYLON;
  41784. (function (BABYLON) {
  41785. /** @hidden */
  41786. var StandardMaterialDefines = /** @class */ (function (_super) {
  41787. __extends(StandardMaterialDefines, _super);
  41788. function StandardMaterialDefines() {
  41789. var _this = _super.call(this) || this;
  41790. _this.MAINUV1 = false;
  41791. _this.MAINUV2 = false;
  41792. _this.DIFFUSE = false;
  41793. _this.DIFFUSEDIRECTUV = 0;
  41794. _this.AMBIENT = false;
  41795. _this.AMBIENTDIRECTUV = 0;
  41796. _this.OPACITY = false;
  41797. _this.OPACITYDIRECTUV = 0;
  41798. _this.OPACITYRGB = false;
  41799. _this.REFLECTION = false;
  41800. _this.EMISSIVE = false;
  41801. _this.EMISSIVEDIRECTUV = 0;
  41802. _this.SPECULAR = false;
  41803. _this.SPECULARDIRECTUV = 0;
  41804. _this.BUMP = false;
  41805. _this.BUMPDIRECTUV = 0;
  41806. _this.PARALLAX = false;
  41807. _this.PARALLAXOCCLUSION = false;
  41808. _this.SPECULAROVERALPHA = false;
  41809. _this.CLIPPLANE = false;
  41810. _this.ALPHATEST = false;
  41811. _this.DEPTHPREPASS = false;
  41812. _this.ALPHAFROMDIFFUSE = false;
  41813. _this.POINTSIZE = false;
  41814. _this.FOG = false;
  41815. _this.SPECULARTERM = false;
  41816. _this.DIFFUSEFRESNEL = false;
  41817. _this.OPACITYFRESNEL = false;
  41818. _this.REFLECTIONFRESNEL = false;
  41819. _this.REFRACTIONFRESNEL = false;
  41820. _this.EMISSIVEFRESNEL = false;
  41821. _this.FRESNEL = false;
  41822. _this.NORMAL = false;
  41823. _this.UV1 = false;
  41824. _this.UV2 = false;
  41825. _this.VERTEXCOLOR = false;
  41826. _this.VERTEXALPHA = false;
  41827. _this.NUM_BONE_INFLUENCERS = 0;
  41828. _this.BonesPerMesh = 0;
  41829. _this.INSTANCES = false;
  41830. _this.GLOSSINESS = false;
  41831. _this.ROUGHNESS = false;
  41832. _this.EMISSIVEASILLUMINATION = false;
  41833. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41834. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41835. _this.LIGHTMAP = false;
  41836. _this.LIGHTMAPDIRECTUV = 0;
  41837. _this.OBJECTSPACE_NORMALMAP = false;
  41838. _this.USELIGHTMAPASSHADOWMAP = false;
  41839. _this.REFLECTIONMAP_3D = false;
  41840. _this.REFLECTIONMAP_SPHERICAL = false;
  41841. _this.REFLECTIONMAP_PLANAR = false;
  41842. _this.REFLECTIONMAP_CUBIC = false;
  41843. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41844. _this.REFLECTIONMAP_PROJECTION = false;
  41845. _this.REFLECTIONMAP_SKYBOX = false;
  41846. _this.REFLECTIONMAP_EXPLICIT = false;
  41847. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41848. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41849. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41850. _this.INVERTCUBICMAP = false;
  41851. _this.LOGARITHMICDEPTH = false;
  41852. _this.REFRACTION = false;
  41853. _this.REFRACTIONMAP_3D = false;
  41854. _this.REFLECTIONOVERALPHA = false;
  41855. _this.TWOSIDEDLIGHTING = false;
  41856. _this.SHADOWFLOAT = false;
  41857. _this.MORPHTARGETS = false;
  41858. _this.MORPHTARGETS_NORMAL = false;
  41859. _this.MORPHTARGETS_TANGENT = false;
  41860. _this.NUM_MORPH_INFLUENCERS = 0;
  41861. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41862. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41863. _this.IMAGEPROCESSING = false;
  41864. _this.VIGNETTE = false;
  41865. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41866. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41867. _this.TONEMAPPING = false;
  41868. _this.CONTRAST = false;
  41869. _this.COLORCURVES = false;
  41870. _this.COLORGRADING = false;
  41871. _this.COLORGRADING3D = false;
  41872. _this.SAMPLER3DGREENDEPTH = false;
  41873. _this.SAMPLER3DBGRMAP = false;
  41874. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41875. /**
  41876. * If the reflection texture on this material is in linear color space
  41877. * @hidden
  41878. */
  41879. _this.IS_REFLECTION_LINEAR = false;
  41880. /**
  41881. * If the refraction texture on this material is in linear color space
  41882. * @hidden
  41883. */
  41884. _this.IS_REFRACTION_LINEAR = false;
  41885. _this.EXPOSURE = false;
  41886. _this.rebuild();
  41887. return _this;
  41888. }
  41889. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41890. var modes = [
  41891. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41892. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41893. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41894. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41895. ];
  41896. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41897. var mode = modes_1[_i];
  41898. this[mode] = (mode === modeToEnable);
  41899. }
  41900. };
  41901. return StandardMaterialDefines;
  41902. }(BABYLON.MaterialDefines));
  41903. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41904. var StandardMaterial = /** @class */ (function (_super) {
  41905. __extends(StandardMaterial, _super);
  41906. function StandardMaterial(name, scene) {
  41907. var _this = _super.call(this, name, scene) || this;
  41908. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41909. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41910. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41911. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41912. _this.specularPower = 64;
  41913. _this._useAlphaFromDiffuseTexture = false;
  41914. _this._useEmissiveAsIllumination = false;
  41915. _this._linkEmissiveWithDiffuse = false;
  41916. _this._useSpecularOverAlpha = false;
  41917. _this._useReflectionOverAlpha = false;
  41918. _this._disableLighting = false;
  41919. _this._useObjectSpaceNormalMap = false;
  41920. _this._useParallax = false;
  41921. _this._useParallaxOcclusion = false;
  41922. _this.parallaxScaleBias = 0.05;
  41923. _this._roughness = 0;
  41924. _this.indexOfRefraction = 0.98;
  41925. _this.invertRefractionY = true;
  41926. /**
  41927. * Defines the alpha limits in alpha test mode
  41928. */
  41929. _this.alphaCutOff = 0.4;
  41930. _this._useLightmapAsShadowmap = false;
  41931. _this._useReflectionFresnelFromSpecular = false;
  41932. _this._useGlossinessFromSpecularMapAlpha = false;
  41933. _this._maxSimultaneousLights = 4;
  41934. /**
  41935. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41936. */
  41937. _this._invertNormalMapX = false;
  41938. /**
  41939. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41940. */
  41941. _this._invertNormalMapY = false;
  41942. /**
  41943. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41944. */
  41945. _this._twoSidedLighting = false;
  41946. _this._renderTargets = new BABYLON.SmartArray(16);
  41947. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41948. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41949. // Setup the default processing configuration to the scene.
  41950. _this._attachImageProcessingConfiguration(null);
  41951. _this.getRenderTargetTextures = function () {
  41952. _this._renderTargets.reset();
  41953. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41954. _this._renderTargets.push(_this._reflectionTexture);
  41955. }
  41956. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41957. _this._renderTargets.push(_this._refractionTexture);
  41958. }
  41959. return _this._renderTargets;
  41960. };
  41961. return _this;
  41962. }
  41963. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41964. /**
  41965. * Gets the image processing configuration used either in this material.
  41966. */
  41967. get: function () {
  41968. return this._imageProcessingConfiguration;
  41969. },
  41970. /**
  41971. * Sets the Default image processing configuration used either in the this material.
  41972. *
  41973. * If sets to null, the scene one is in use.
  41974. */
  41975. set: function (value) {
  41976. this._attachImageProcessingConfiguration(value);
  41977. // Ensure the effect will be rebuilt.
  41978. this._markAllSubMeshesAsTexturesDirty();
  41979. },
  41980. enumerable: true,
  41981. configurable: true
  41982. });
  41983. /**
  41984. * Attaches a new image processing configuration to the Standard Material.
  41985. * @param configuration
  41986. */
  41987. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41988. var _this = this;
  41989. if (configuration === this._imageProcessingConfiguration) {
  41990. return;
  41991. }
  41992. // Detaches observer.
  41993. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41994. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41995. }
  41996. // Pick the scene configuration if needed.
  41997. if (!configuration) {
  41998. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41999. }
  42000. else {
  42001. this._imageProcessingConfiguration = configuration;
  42002. }
  42003. // Attaches observer.
  42004. if (this._imageProcessingConfiguration) {
  42005. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42006. _this._markAllSubMeshesAsImageProcessingDirty();
  42007. });
  42008. }
  42009. };
  42010. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42011. /**
  42012. * Gets wether the color curves effect is enabled.
  42013. */
  42014. get: function () {
  42015. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42016. },
  42017. /**
  42018. * Sets wether the color curves effect is enabled.
  42019. */
  42020. set: function (value) {
  42021. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42022. },
  42023. enumerable: true,
  42024. configurable: true
  42025. });
  42026. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42027. /**
  42028. * Gets wether the color grading effect is enabled.
  42029. */
  42030. get: function () {
  42031. return this.imageProcessingConfiguration.colorGradingEnabled;
  42032. },
  42033. /**
  42034. * Gets wether the color grading effect is enabled.
  42035. */
  42036. set: function (value) {
  42037. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42038. },
  42039. enumerable: true,
  42040. configurable: true
  42041. });
  42042. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42043. /**
  42044. * Gets wether tonemapping is enabled or not.
  42045. */
  42046. get: function () {
  42047. return this._imageProcessingConfiguration.toneMappingEnabled;
  42048. },
  42049. /**
  42050. * Sets wether tonemapping is enabled or not
  42051. */
  42052. set: function (value) {
  42053. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42054. },
  42055. enumerable: true,
  42056. configurable: true
  42057. });
  42058. ;
  42059. ;
  42060. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42061. /**
  42062. * The camera exposure used on this material.
  42063. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42064. * This corresponds to a photographic exposure.
  42065. */
  42066. get: function () {
  42067. return this._imageProcessingConfiguration.exposure;
  42068. },
  42069. /**
  42070. * The camera exposure used on this material.
  42071. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42072. * This corresponds to a photographic exposure.
  42073. */
  42074. set: function (value) {
  42075. this._imageProcessingConfiguration.exposure = value;
  42076. },
  42077. enumerable: true,
  42078. configurable: true
  42079. });
  42080. ;
  42081. ;
  42082. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42083. /**
  42084. * Gets The camera contrast used on this material.
  42085. */
  42086. get: function () {
  42087. return this._imageProcessingConfiguration.contrast;
  42088. },
  42089. /**
  42090. * Sets The camera contrast used on this material.
  42091. */
  42092. set: function (value) {
  42093. this._imageProcessingConfiguration.contrast = value;
  42094. },
  42095. enumerable: true,
  42096. configurable: true
  42097. });
  42098. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42099. /**
  42100. * Gets the Color Grading 2D Lookup Texture.
  42101. */
  42102. get: function () {
  42103. return this._imageProcessingConfiguration.colorGradingTexture;
  42104. },
  42105. /**
  42106. * Sets the Color Grading 2D Lookup Texture.
  42107. */
  42108. set: function (value) {
  42109. this._imageProcessingConfiguration.colorGradingTexture = value;
  42110. },
  42111. enumerable: true,
  42112. configurable: true
  42113. });
  42114. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42115. /**
  42116. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42117. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42118. * 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;
  42119. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42120. */
  42121. get: function () {
  42122. return this._imageProcessingConfiguration.colorCurves;
  42123. },
  42124. /**
  42125. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42126. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42127. * 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;
  42128. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42129. */
  42130. set: function (value) {
  42131. this._imageProcessingConfiguration.colorCurves = value;
  42132. },
  42133. enumerable: true,
  42134. configurable: true
  42135. });
  42136. StandardMaterial.prototype.getClassName = function () {
  42137. return "StandardMaterial";
  42138. };
  42139. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42140. get: function () {
  42141. return this._useLogarithmicDepth;
  42142. },
  42143. set: function (value) {
  42144. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42145. this._markAllSubMeshesAsMiscDirty();
  42146. },
  42147. enumerable: true,
  42148. configurable: true
  42149. });
  42150. StandardMaterial.prototype.needAlphaBlending = function () {
  42151. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42152. };
  42153. StandardMaterial.prototype.needAlphaTesting = function () {
  42154. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42155. };
  42156. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42157. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42158. };
  42159. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42160. return this._diffuseTexture;
  42161. };
  42162. /**
  42163. * Child classes can use it to update shaders
  42164. */
  42165. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42166. if (useInstances === void 0) { useInstances = false; }
  42167. if (subMesh.effect && this.isFrozen) {
  42168. if (this._wasPreviouslyReady && subMesh.effect) {
  42169. return true;
  42170. }
  42171. }
  42172. if (!subMesh._materialDefines) {
  42173. subMesh._materialDefines = new StandardMaterialDefines();
  42174. }
  42175. var scene = this.getScene();
  42176. var defines = subMesh._materialDefines;
  42177. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42178. if (defines._renderId === scene.getRenderId()) {
  42179. return true;
  42180. }
  42181. }
  42182. var engine = scene.getEngine();
  42183. // Lights
  42184. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42185. // Textures
  42186. if (defines._areTexturesDirty) {
  42187. defines._needUVs = false;
  42188. defines.MAINUV1 = false;
  42189. defines.MAINUV2 = false;
  42190. if (scene.texturesEnabled) {
  42191. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42192. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42193. return false;
  42194. }
  42195. else {
  42196. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42197. }
  42198. }
  42199. else {
  42200. defines.DIFFUSE = false;
  42201. }
  42202. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42203. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42204. return false;
  42205. }
  42206. else {
  42207. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42208. }
  42209. }
  42210. else {
  42211. defines.AMBIENT = false;
  42212. }
  42213. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42214. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42215. return false;
  42216. }
  42217. else {
  42218. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42219. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42220. }
  42221. }
  42222. else {
  42223. defines.OPACITY = false;
  42224. }
  42225. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42226. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42227. return false;
  42228. }
  42229. else {
  42230. defines._needNormals = true;
  42231. defines.REFLECTION = true;
  42232. defines.ROUGHNESS = (this._roughness > 0);
  42233. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42234. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42235. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42236. switch (this._reflectionTexture.coordinatesMode) {
  42237. case BABYLON.Texture.EXPLICIT_MODE:
  42238. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42239. break;
  42240. case BABYLON.Texture.PLANAR_MODE:
  42241. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42242. break;
  42243. case BABYLON.Texture.PROJECTION_MODE:
  42244. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42245. break;
  42246. case BABYLON.Texture.SKYBOX_MODE:
  42247. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42248. break;
  42249. case BABYLON.Texture.SPHERICAL_MODE:
  42250. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42251. break;
  42252. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42253. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42254. break;
  42255. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42256. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42257. break;
  42258. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42259. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42260. break;
  42261. case BABYLON.Texture.CUBIC_MODE:
  42262. case BABYLON.Texture.INVCUBIC_MODE:
  42263. default:
  42264. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42265. break;
  42266. }
  42267. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42268. }
  42269. }
  42270. else {
  42271. defines.REFLECTION = false;
  42272. }
  42273. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42274. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42275. return false;
  42276. }
  42277. else {
  42278. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42279. }
  42280. }
  42281. else {
  42282. defines.EMISSIVE = false;
  42283. }
  42284. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42285. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42286. return false;
  42287. }
  42288. else {
  42289. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42290. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42291. }
  42292. }
  42293. else {
  42294. defines.LIGHTMAP = false;
  42295. }
  42296. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42297. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42298. return false;
  42299. }
  42300. else {
  42301. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42302. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42303. }
  42304. }
  42305. else {
  42306. defines.SPECULAR = false;
  42307. }
  42308. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42309. // Bump texure can not be not blocking.
  42310. if (!this._bumpTexture.isReady()) {
  42311. return false;
  42312. }
  42313. else {
  42314. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42315. defines.PARALLAX = this._useParallax;
  42316. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42317. }
  42318. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42319. }
  42320. else {
  42321. defines.BUMP = false;
  42322. }
  42323. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42324. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42325. return false;
  42326. }
  42327. else {
  42328. defines._needUVs = true;
  42329. defines.REFRACTION = true;
  42330. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42331. }
  42332. }
  42333. else {
  42334. defines.REFRACTION = false;
  42335. }
  42336. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42337. }
  42338. else {
  42339. defines.DIFFUSE = false;
  42340. defines.AMBIENT = false;
  42341. defines.OPACITY = false;
  42342. defines.REFLECTION = false;
  42343. defines.EMISSIVE = false;
  42344. defines.LIGHTMAP = false;
  42345. defines.BUMP = false;
  42346. defines.REFRACTION = false;
  42347. }
  42348. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42349. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42350. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42351. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42352. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42353. }
  42354. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42355. if (!this._imageProcessingConfiguration.isReady()) {
  42356. return false;
  42357. }
  42358. this._imageProcessingConfiguration.prepareDefines(defines);
  42359. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42360. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42361. }
  42362. if (defines._areFresnelDirty) {
  42363. if (StandardMaterial.FresnelEnabled) {
  42364. // Fresnel
  42365. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42366. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42367. this._reflectionFresnelParameters) {
  42368. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42369. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42370. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42371. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42372. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42373. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42374. defines._needNormals = true;
  42375. defines.FRESNEL = true;
  42376. }
  42377. }
  42378. else {
  42379. defines.FRESNEL = false;
  42380. }
  42381. }
  42382. // Misc.
  42383. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42384. // Attribs
  42385. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42386. // Values that need to be evaluated on every frame
  42387. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42388. // Get correct effect
  42389. if (defines.isDirty) {
  42390. defines.markAsProcessed();
  42391. scene.resetCachedMaterial();
  42392. // Fallbacks
  42393. var fallbacks = new BABYLON.EffectFallbacks();
  42394. if (defines.REFLECTION) {
  42395. fallbacks.addFallback(0, "REFLECTION");
  42396. }
  42397. if (defines.SPECULAR) {
  42398. fallbacks.addFallback(0, "SPECULAR");
  42399. }
  42400. if (defines.BUMP) {
  42401. fallbacks.addFallback(0, "BUMP");
  42402. }
  42403. if (defines.PARALLAX) {
  42404. fallbacks.addFallback(1, "PARALLAX");
  42405. }
  42406. if (defines.PARALLAXOCCLUSION) {
  42407. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42408. }
  42409. if (defines.SPECULAROVERALPHA) {
  42410. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42411. }
  42412. if (defines.FOG) {
  42413. fallbacks.addFallback(1, "FOG");
  42414. }
  42415. if (defines.POINTSIZE) {
  42416. fallbacks.addFallback(0, "POINTSIZE");
  42417. }
  42418. if (defines.LOGARITHMICDEPTH) {
  42419. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42420. }
  42421. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42422. if (defines.SPECULARTERM) {
  42423. fallbacks.addFallback(0, "SPECULARTERM");
  42424. }
  42425. if (defines.DIFFUSEFRESNEL) {
  42426. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42427. }
  42428. if (defines.OPACITYFRESNEL) {
  42429. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42430. }
  42431. if (defines.REFLECTIONFRESNEL) {
  42432. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42433. }
  42434. if (defines.EMISSIVEFRESNEL) {
  42435. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42436. }
  42437. if (defines.FRESNEL) {
  42438. fallbacks.addFallback(4, "FRESNEL");
  42439. }
  42440. //Attributes
  42441. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42442. if (defines.NORMAL) {
  42443. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42444. }
  42445. if (defines.UV1) {
  42446. attribs.push(BABYLON.VertexBuffer.UVKind);
  42447. }
  42448. if (defines.UV2) {
  42449. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42450. }
  42451. if (defines.VERTEXCOLOR) {
  42452. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42453. }
  42454. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42455. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42456. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42457. var shaderName = "default";
  42458. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42459. "vFogInfos", "vFogColor", "pointSize",
  42460. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42461. "mBones",
  42462. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42463. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42464. "vReflectionPosition", "vReflectionSize",
  42465. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42466. ];
  42467. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42468. var uniformBuffers = ["Material", "Scene"];
  42469. if (BABYLON.ImageProcessingConfiguration) {
  42470. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42471. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42472. }
  42473. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42474. uniformsNames: uniforms,
  42475. uniformBuffersNames: uniformBuffers,
  42476. samplers: samplers,
  42477. defines: defines,
  42478. maxSimultaneousLights: this._maxSimultaneousLights
  42479. });
  42480. if (this.customShaderNameResolve) {
  42481. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42482. }
  42483. var join = defines.toString();
  42484. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42485. attributes: attribs,
  42486. uniformsNames: uniforms,
  42487. uniformBuffersNames: uniformBuffers,
  42488. samplers: samplers,
  42489. defines: join,
  42490. fallbacks: fallbacks,
  42491. onCompiled: this.onCompiled,
  42492. onError: this.onError,
  42493. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42494. }, engine), defines);
  42495. this.buildUniformLayout();
  42496. }
  42497. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42498. return false;
  42499. }
  42500. defines._renderId = scene.getRenderId();
  42501. this._wasPreviouslyReady = true;
  42502. return true;
  42503. };
  42504. StandardMaterial.prototype.buildUniformLayout = function () {
  42505. // Order is important !
  42506. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42507. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42508. this._uniformBuffer.addUniform("opacityParts", 4);
  42509. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42510. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42511. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42512. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42513. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42514. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42515. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42516. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42517. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42518. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42519. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42520. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42521. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42522. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42523. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42524. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42525. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42526. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42527. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42528. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42529. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42530. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42531. this._uniformBuffer.addUniform("specularMatrix", 16);
  42532. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42533. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42534. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42535. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42536. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42537. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42538. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42539. this._uniformBuffer.addUniform("pointSize", 1);
  42540. this._uniformBuffer.create();
  42541. };
  42542. StandardMaterial.prototype.unbind = function () {
  42543. if (this._activeEffect) {
  42544. var needFlag = false;
  42545. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42546. this._activeEffect.setTexture("reflection2DSampler", null);
  42547. needFlag = true;
  42548. }
  42549. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42550. this._activeEffect.setTexture("refraction2DSampler", null);
  42551. needFlag = true;
  42552. }
  42553. if (needFlag) {
  42554. this._markAllSubMeshesAsTexturesDirty();
  42555. }
  42556. }
  42557. _super.prototype.unbind.call(this);
  42558. };
  42559. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42560. var scene = this.getScene();
  42561. var defines = subMesh._materialDefines;
  42562. if (!defines) {
  42563. return;
  42564. }
  42565. var effect = subMesh.effect;
  42566. if (!effect) {
  42567. return;
  42568. }
  42569. this._activeEffect = effect;
  42570. // Matrices
  42571. this.bindOnlyWorldMatrix(world);
  42572. // Normal Matrix
  42573. if (defines.OBJECTSPACE_NORMALMAP) {
  42574. world.toNormalMatrix(this._normalMatrix);
  42575. this.bindOnlyNormalMatrix(this._normalMatrix);
  42576. }
  42577. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42578. // Bones
  42579. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42580. if (mustRebind) {
  42581. this._uniformBuffer.bindToEffect(effect, "Material");
  42582. this.bindViewProjection(effect);
  42583. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42584. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42585. // Fresnel
  42586. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42587. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42588. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42589. }
  42590. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42591. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42592. }
  42593. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42594. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42595. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42596. }
  42597. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42598. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42599. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42600. }
  42601. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42602. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42603. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42604. }
  42605. }
  42606. // Textures
  42607. if (scene.texturesEnabled) {
  42608. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42609. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42610. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42611. if (this._diffuseTexture.hasAlpha) {
  42612. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42613. }
  42614. }
  42615. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42616. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42617. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42618. }
  42619. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42620. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42621. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42622. }
  42623. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42624. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42625. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42626. if (this._reflectionTexture.boundingBoxSize) {
  42627. var cubeTexture = this._reflectionTexture;
  42628. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42629. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42630. }
  42631. }
  42632. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42633. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42634. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42635. }
  42636. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42637. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42638. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42639. }
  42640. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42641. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42642. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42643. }
  42644. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42645. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42646. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42647. if (scene._mirroredCameraPosition) {
  42648. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42649. }
  42650. else {
  42651. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42652. }
  42653. }
  42654. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42655. var depth = 1.0;
  42656. if (!this._refractionTexture.isCube) {
  42657. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42658. if (this._refractionTexture.depth) {
  42659. depth = this._refractionTexture.depth;
  42660. }
  42661. }
  42662. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42663. }
  42664. }
  42665. // Point size
  42666. if (this.pointsCloud) {
  42667. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42668. }
  42669. if (defines.SPECULARTERM) {
  42670. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42671. }
  42672. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42673. // Diffuse
  42674. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42675. }
  42676. // Textures
  42677. if (scene.texturesEnabled) {
  42678. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42679. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42680. }
  42681. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42682. effect.setTexture("ambientSampler", this._ambientTexture);
  42683. }
  42684. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42685. effect.setTexture("opacitySampler", this._opacityTexture);
  42686. }
  42687. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42688. if (this._reflectionTexture.isCube) {
  42689. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42690. }
  42691. else {
  42692. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42693. }
  42694. }
  42695. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42696. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42697. }
  42698. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42699. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42700. }
  42701. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42702. effect.setTexture("specularSampler", this._specularTexture);
  42703. }
  42704. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42705. effect.setTexture("bumpSampler", this._bumpTexture);
  42706. }
  42707. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42708. var depth = 1.0;
  42709. if (this._refractionTexture.isCube) {
  42710. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42711. }
  42712. else {
  42713. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42714. }
  42715. }
  42716. }
  42717. // Clip plane
  42718. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42719. // Colors
  42720. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42721. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42722. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42723. }
  42724. if (mustRebind || !this.isFrozen) {
  42725. // Lights
  42726. if (scene.lightsEnabled && !this._disableLighting) {
  42727. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42728. }
  42729. // View
  42730. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42731. this.bindView(effect);
  42732. }
  42733. // Fog
  42734. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42735. // Morph targets
  42736. if (defines.NUM_MORPH_INFLUENCERS) {
  42737. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42738. }
  42739. // Log. depth
  42740. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42741. // image processing
  42742. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42743. this._imageProcessingConfiguration.bind(this._activeEffect);
  42744. }
  42745. }
  42746. this._uniformBuffer.update();
  42747. this._afterBind(mesh, this._activeEffect);
  42748. };
  42749. StandardMaterial.prototype.getAnimatables = function () {
  42750. var results = [];
  42751. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42752. results.push(this._diffuseTexture);
  42753. }
  42754. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42755. results.push(this._ambientTexture);
  42756. }
  42757. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42758. results.push(this._opacityTexture);
  42759. }
  42760. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42761. results.push(this._reflectionTexture);
  42762. }
  42763. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42764. results.push(this._emissiveTexture);
  42765. }
  42766. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42767. results.push(this._specularTexture);
  42768. }
  42769. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42770. results.push(this._bumpTexture);
  42771. }
  42772. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42773. results.push(this._lightmapTexture);
  42774. }
  42775. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42776. results.push(this._refractionTexture);
  42777. }
  42778. return results;
  42779. };
  42780. StandardMaterial.prototype.getActiveTextures = function () {
  42781. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42782. if (this._diffuseTexture) {
  42783. activeTextures.push(this._diffuseTexture);
  42784. }
  42785. if (this._ambientTexture) {
  42786. activeTextures.push(this._ambientTexture);
  42787. }
  42788. if (this._opacityTexture) {
  42789. activeTextures.push(this._opacityTexture);
  42790. }
  42791. if (this._reflectionTexture) {
  42792. activeTextures.push(this._reflectionTexture);
  42793. }
  42794. if (this._emissiveTexture) {
  42795. activeTextures.push(this._emissiveTexture);
  42796. }
  42797. if (this._specularTexture) {
  42798. activeTextures.push(this._specularTexture);
  42799. }
  42800. if (this._bumpTexture) {
  42801. activeTextures.push(this._bumpTexture);
  42802. }
  42803. if (this._lightmapTexture) {
  42804. activeTextures.push(this._lightmapTexture);
  42805. }
  42806. if (this._refractionTexture) {
  42807. activeTextures.push(this._refractionTexture);
  42808. }
  42809. return activeTextures;
  42810. };
  42811. StandardMaterial.prototype.hasTexture = function (texture) {
  42812. if (_super.prototype.hasTexture.call(this, texture)) {
  42813. return true;
  42814. }
  42815. if (this._diffuseTexture === texture) {
  42816. return true;
  42817. }
  42818. if (this._ambientTexture === texture) {
  42819. return true;
  42820. }
  42821. if (this._opacityTexture === texture) {
  42822. return true;
  42823. }
  42824. if (this._reflectionTexture === texture) {
  42825. return true;
  42826. }
  42827. if (this._emissiveTexture === texture) {
  42828. return true;
  42829. }
  42830. if (this._specularTexture === texture) {
  42831. return true;
  42832. }
  42833. if (this._bumpTexture === texture) {
  42834. return true;
  42835. }
  42836. if (this._lightmapTexture === texture) {
  42837. return true;
  42838. }
  42839. if (this._refractionTexture === texture) {
  42840. return true;
  42841. }
  42842. return false;
  42843. };
  42844. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42845. if (forceDisposeTextures) {
  42846. if (this._diffuseTexture) {
  42847. this._diffuseTexture.dispose();
  42848. }
  42849. if (this._ambientTexture) {
  42850. this._ambientTexture.dispose();
  42851. }
  42852. if (this._opacityTexture) {
  42853. this._opacityTexture.dispose();
  42854. }
  42855. if (this._reflectionTexture) {
  42856. this._reflectionTexture.dispose();
  42857. }
  42858. if (this._emissiveTexture) {
  42859. this._emissiveTexture.dispose();
  42860. }
  42861. if (this._specularTexture) {
  42862. this._specularTexture.dispose();
  42863. }
  42864. if (this._bumpTexture) {
  42865. this._bumpTexture.dispose();
  42866. }
  42867. if (this._lightmapTexture) {
  42868. this._lightmapTexture.dispose();
  42869. }
  42870. if (this._refractionTexture) {
  42871. this._refractionTexture.dispose();
  42872. }
  42873. }
  42874. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42875. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42876. }
  42877. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42878. };
  42879. StandardMaterial.prototype.clone = function (name) {
  42880. var _this = this;
  42881. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42882. result.name = name;
  42883. result.id = name;
  42884. return result;
  42885. };
  42886. StandardMaterial.prototype.serialize = function () {
  42887. return BABYLON.SerializationHelper.Serialize(this);
  42888. };
  42889. // Statics
  42890. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42891. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42892. };
  42893. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42894. get: function () {
  42895. return StandardMaterial._DiffuseTextureEnabled;
  42896. },
  42897. set: function (value) {
  42898. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42899. return;
  42900. }
  42901. StandardMaterial._DiffuseTextureEnabled = value;
  42902. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42903. },
  42904. enumerable: true,
  42905. configurable: true
  42906. });
  42907. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42908. get: function () {
  42909. return StandardMaterial._AmbientTextureEnabled;
  42910. },
  42911. set: function (value) {
  42912. if (StandardMaterial._AmbientTextureEnabled === value) {
  42913. return;
  42914. }
  42915. StandardMaterial._AmbientTextureEnabled = value;
  42916. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42922. get: function () {
  42923. return StandardMaterial._OpacityTextureEnabled;
  42924. },
  42925. set: function (value) {
  42926. if (StandardMaterial._OpacityTextureEnabled === value) {
  42927. return;
  42928. }
  42929. StandardMaterial._OpacityTextureEnabled = value;
  42930. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42931. },
  42932. enumerable: true,
  42933. configurable: true
  42934. });
  42935. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42936. get: function () {
  42937. return StandardMaterial._ReflectionTextureEnabled;
  42938. },
  42939. set: function (value) {
  42940. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42941. return;
  42942. }
  42943. StandardMaterial._ReflectionTextureEnabled = value;
  42944. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42945. },
  42946. enumerable: true,
  42947. configurable: true
  42948. });
  42949. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42950. get: function () {
  42951. return StandardMaterial._EmissiveTextureEnabled;
  42952. },
  42953. set: function (value) {
  42954. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42955. return;
  42956. }
  42957. StandardMaterial._EmissiveTextureEnabled = value;
  42958. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42959. },
  42960. enumerable: true,
  42961. configurable: true
  42962. });
  42963. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42964. get: function () {
  42965. return StandardMaterial._SpecularTextureEnabled;
  42966. },
  42967. set: function (value) {
  42968. if (StandardMaterial._SpecularTextureEnabled === value) {
  42969. return;
  42970. }
  42971. StandardMaterial._SpecularTextureEnabled = value;
  42972. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42973. },
  42974. enumerable: true,
  42975. configurable: true
  42976. });
  42977. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42978. get: function () {
  42979. return StandardMaterial._BumpTextureEnabled;
  42980. },
  42981. set: function (value) {
  42982. if (StandardMaterial._BumpTextureEnabled === value) {
  42983. return;
  42984. }
  42985. StandardMaterial._BumpTextureEnabled = value;
  42986. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42987. },
  42988. enumerable: true,
  42989. configurable: true
  42990. });
  42991. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42992. get: function () {
  42993. return StandardMaterial._LightmapTextureEnabled;
  42994. },
  42995. set: function (value) {
  42996. if (StandardMaterial._LightmapTextureEnabled === value) {
  42997. return;
  42998. }
  42999. StandardMaterial._LightmapTextureEnabled = value;
  43000. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43001. },
  43002. enumerable: true,
  43003. configurable: true
  43004. });
  43005. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43006. get: function () {
  43007. return StandardMaterial._RefractionTextureEnabled;
  43008. },
  43009. set: function (value) {
  43010. if (StandardMaterial._RefractionTextureEnabled === value) {
  43011. return;
  43012. }
  43013. StandardMaterial._RefractionTextureEnabled = value;
  43014. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43015. },
  43016. enumerable: true,
  43017. configurable: true
  43018. });
  43019. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43020. get: function () {
  43021. return StandardMaterial._ColorGradingTextureEnabled;
  43022. },
  43023. set: function (value) {
  43024. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43025. return;
  43026. }
  43027. StandardMaterial._ColorGradingTextureEnabled = value;
  43028. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43029. },
  43030. enumerable: true,
  43031. configurable: true
  43032. });
  43033. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43034. get: function () {
  43035. return StandardMaterial._FresnelEnabled;
  43036. },
  43037. set: function (value) {
  43038. if (StandardMaterial._FresnelEnabled === value) {
  43039. return;
  43040. }
  43041. StandardMaterial._FresnelEnabled = value;
  43042. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43043. },
  43044. enumerable: true,
  43045. configurable: true
  43046. });
  43047. // Flags used to enable or disable a type of texture for all Standard Materials
  43048. StandardMaterial._DiffuseTextureEnabled = true;
  43049. StandardMaterial._AmbientTextureEnabled = true;
  43050. StandardMaterial._OpacityTextureEnabled = true;
  43051. StandardMaterial._ReflectionTextureEnabled = true;
  43052. StandardMaterial._EmissiveTextureEnabled = true;
  43053. StandardMaterial._SpecularTextureEnabled = true;
  43054. StandardMaterial._BumpTextureEnabled = true;
  43055. StandardMaterial._LightmapTextureEnabled = true;
  43056. StandardMaterial._RefractionTextureEnabled = true;
  43057. StandardMaterial._ColorGradingTextureEnabled = true;
  43058. StandardMaterial._FresnelEnabled = true;
  43059. __decorate([
  43060. BABYLON.serializeAsTexture("diffuseTexture")
  43061. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43062. __decorate([
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43064. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43065. __decorate([
  43066. BABYLON.serializeAsTexture("ambientTexture")
  43067. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43068. __decorate([
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43071. __decorate([
  43072. BABYLON.serializeAsTexture("opacityTexture")
  43073. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43074. __decorate([
  43075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43076. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43077. __decorate([
  43078. BABYLON.serializeAsTexture("reflectionTexture")
  43079. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43080. __decorate([
  43081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43082. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43083. __decorate([
  43084. BABYLON.serializeAsTexture("emissiveTexture")
  43085. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43086. __decorate([
  43087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43088. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43089. __decorate([
  43090. BABYLON.serializeAsTexture("specularTexture")
  43091. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43092. __decorate([
  43093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43094. ], StandardMaterial.prototype, "specularTexture", void 0);
  43095. __decorate([
  43096. BABYLON.serializeAsTexture("bumpTexture")
  43097. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43098. __decorate([
  43099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43100. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43101. __decorate([
  43102. BABYLON.serializeAsTexture("lightmapTexture")
  43103. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43104. __decorate([
  43105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43106. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43107. __decorate([
  43108. BABYLON.serializeAsTexture("refractionTexture")
  43109. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43110. __decorate([
  43111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43112. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43113. __decorate([
  43114. BABYLON.serializeAsColor3("ambient")
  43115. ], StandardMaterial.prototype, "ambientColor", void 0);
  43116. __decorate([
  43117. BABYLON.serializeAsColor3("diffuse")
  43118. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43119. __decorate([
  43120. BABYLON.serializeAsColor3("specular")
  43121. ], StandardMaterial.prototype, "specularColor", void 0);
  43122. __decorate([
  43123. BABYLON.serializeAsColor3("emissive")
  43124. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43125. __decorate([
  43126. BABYLON.serialize()
  43127. ], StandardMaterial.prototype, "specularPower", void 0);
  43128. __decorate([
  43129. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43130. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43131. __decorate([
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43134. __decorate([
  43135. BABYLON.serialize("useEmissiveAsIllumination")
  43136. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43137. __decorate([
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43139. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43140. __decorate([
  43141. BABYLON.serialize("linkEmissiveWithDiffuse")
  43142. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43143. __decorate([
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43145. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43146. __decorate([
  43147. BABYLON.serialize("useSpecularOverAlpha")
  43148. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43149. __decorate([
  43150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43151. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43152. __decorate([
  43153. BABYLON.serialize("useReflectionOverAlpha")
  43154. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43155. __decorate([
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43158. __decorate([
  43159. BABYLON.serialize("disableLighting")
  43160. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43161. __decorate([
  43162. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43163. ], StandardMaterial.prototype, "disableLighting", void 0);
  43164. __decorate([
  43165. BABYLON.serialize("useObjectSpaceNormalMap")
  43166. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43167. __decorate([
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43169. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43170. __decorate([
  43171. BABYLON.serialize("useParallax")
  43172. ], StandardMaterial.prototype, "_useParallax", void 0);
  43173. __decorate([
  43174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43175. ], StandardMaterial.prototype, "useParallax", void 0);
  43176. __decorate([
  43177. BABYLON.serialize("useParallaxOcclusion")
  43178. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43179. __decorate([
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43181. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43182. __decorate([
  43183. BABYLON.serialize()
  43184. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43185. __decorate([
  43186. BABYLON.serialize("roughness")
  43187. ], StandardMaterial.prototype, "_roughness", void 0);
  43188. __decorate([
  43189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43190. ], StandardMaterial.prototype, "roughness", void 0);
  43191. __decorate([
  43192. BABYLON.serialize()
  43193. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43194. __decorate([
  43195. BABYLON.serialize()
  43196. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43197. __decorate([
  43198. BABYLON.serialize()
  43199. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43200. __decorate([
  43201. BABYLON.serialize("useLightmapAsShadowmap")
  43202. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43203. __decorate([
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43205. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43206. __decorate([
  43207. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43208. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43209. __decorate([
  43210. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43211. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43212. __decorate([
  43213. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43214. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43215. __decorate([
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43217. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43218. __decorate([
  43219. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43220. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43221. __decorate([
  43222. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43223. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43224. __decorate([
  43225. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43226. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43227. __decorate([
  43228. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43229. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43230. __decorate([
  43231. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43232. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43233. __decorate([
  43234. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43235. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43236. __decorate([
  43237. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43238. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43239. __decorate([
  43240. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43241. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43242. __decorate([
  43243. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43244. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43245. __decorate([
  43246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43247. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43248. __decorate([
  43249. BABYLON.serialize("maxSimultaneousLights")
  43250. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43251. __decorate([
  43252. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43253. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43254. __decorate([
  43255. BABYLON.serialize("invertNormalMapX")
  43256. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43257. __decorate([
  43258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43259. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43260. __decorate([
  43261. BABYLON.serialize("invertNormalMapY")
  43262. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43263. __decorate([
  43264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43265. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43266. __decorate([
  43267. BABYLON.serialize("twoSidedLighting")
  43268. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43269. __decorate([
  43270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43271. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43272. __decorate([
  43273. BABYLON.serialize()
  43274. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43275. return StandardMaterial;
  43276. }(BABYLON.PushMaterial));
  43277. BABYLON.StandardMaterial = StandardMaterial;
  43278. })(BABYLON || (BABYLON = {}));
  43279. //# sourceMappingURL=babylon.standardMaterial.js.map
  43280. var BABYLON;
  43281. (function (BABYLON) {
  43282. /**
  43283. * Manages the defines for the PBR Material.
  43284. * @hiddenChildren
  43285. */
  43286. var PBRMaterialDefines = /** @class */ (function (_super) {
  43287. __extends(PBRMaterialDefines, _super);
  43288. /**
  43289. * Initializes the PBR Material defines.
  43290. */
  43291. function PBRMaterialDefines() {
  43292. var _this = _super.call(this) || this;
  43293. _this.PBR = true;
  43294. _this.MAINUV1 = false;
  43295. _this.MAINUV2 = false;
  43296. _this.UV1 = false;
  43297. _this.UV2 = false;
  43298. _this.ALBEDO = false;
  43299. _this.ALBEDODIRECTUV = 0;
  43300. _this.VERTEXCOLOR = false;
  43301. _this.AMBIENT = false;
  43302. _this.AMBIENTDIRECTUV = 0;
  43303. _this.AMBIENTINGRAYSCALE = false;
  43304. _this.OPACITY = false;
  43305. _this.VERTEXALPHA = false;
  43306. _this.OPACITYDIRECTUV = 0;
  43307. _this.OPACITYRGB = false;
  43308. _this.ALPHATEST = false;
  43309. _this.DEPTHPREPASS = false;
  43310. _this.ALPHABLEND = false;
  43311. _this.ALPHAFROMALBEDO = false;
  43312. _this.ALPHATESTVALUE = "0.5";
  43313. _this.SPECULAROVERALPHA = false;
  43314. _this.RADIANCEOVERALPHA = false;
  43315. _this.ALPHAFRESNEL = false;
  43316. _this.LINEARALPHAFRESNEL = false;
  43317. _this.PREMULTIPLYALPHA = false;
  43318. _this.EMISSIVE = false;
  43319. _this.EMISSIVEDIRECTUV = 0;
  43320. _this.REFLECTIVITY = false;
  43321. _this.REFLECTIVITYDIRECTUV = 0;
  43322. _this.SPECULARTERM = false;
  43323. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43324. _this.MICROSURFACEAUTOMATIC = false;
  43325. _this.LODBASEDMICROSFURACE = false;
  43326. _this.MICROSURFACEMAP = false;
  43327. _this.MICROSURFACEMAPDIRECTUV = 0;
  43328. _this.METALLICWORKFLOW = false;
  43329. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43330. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43331. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43332. _this.AOSTOREINMETALMAPRED = false;
  43333. _this.ENVIRONMENTBRDF = false;
  43334. _this.NORMAL = false;
  43335. _this.TANGENT = false;
  43336. _this.BUMP = false;
  43337. _this.BUMPDIRECTUV = 0;
  43338. _this.OBJECTSPACE_NORMALMAP = false;
  43339. _this.PARALLAX = false;
  43340. _this.PARALLAXOCCLUSION = false;
  43341. _this.NORMALXYSCALE = true;
  43342. _this.LIGHTMAP = false;
  43343. _this.LIGHTMAPDIRECTUV = 0;
  43344. _this.USELIGHTMAPASSHADOWMAP = false;
  43345. _this.GAMMALIGHTMAP = false;
  43346. _this.REFLECTION = false;
  43347. _this.REFLECTIONMAP_3D = false;
  43348. _this.REFLECTIONMAP_SPHERICAL = false;
  43349. _this.REFLECTIONMAP_PLANAR = false;
  43350. _this.REFLECTIONMAP_CUBIC = false;
  43351. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43352. _this.REFLECTIONMAP_PROJECTION = false;
  43353. _this.REFLECTIONMAP_SKYBOX = false;
  43354. _this.REFLECTIONMAP_EXPLICIT = false;
  43355. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43356. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43357. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43358. _this.INVERTCUBICMAP = false;
  43359. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43360. _this.USESPHERICALINVERTEX = false;
  43361. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43362. _this.LODINREFLECTIONALPHA = false;
  43363. _this.GAMMAREFLECTION = false;
  43364. _this.RGBDREFLECTION = false;
  43365. _this.RADIANCEOCCLUSION = false;
  43366. _this.HORIZONOCCLUSION = false;
  43367. _this.REFRACTION = false;
  43368. _this.REFRACTIONMAP_3D = false;
  43369. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43370. _this.LODINREFRACTIONALPHA = false;
  43371. _this.GAMMAREFRACTION = false;
  43372. _this.RGBDREFRACTION = false;
  43373. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43374. _this.INSTANCES = false;
  43375. _this.NUM_BONE_INFLUENCERS = 0;
  43376. _this.BonesPerMesh = 0;
  43377. _this.NONUNIFORMSCALING = false;
  43378. _this.MORPHTARGETS = false;
  43379. _this.MORPHTARGETS_NORMAL = false;
  43380. _this.MORPHTARGETS_TANGENT = false;
  43381. _this.NUM_MORPH_INFLUENCERS = 0;
  43382. _this.IMAGEPROCESSING = false;
  43383. _this.VIGNETTE = false;
  43384. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43385. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43386. _this.TONEMAPPING = false;
  43387. _this.CONTRAST = false;
  43388. _this.COLORCURVES = false;
  43389. _this.COLORGRADING = false;
  43390. _this.COLORGRADING3D = false;
  43391. _this.SAMPLER3DGREENDEPTH = false;
  43392. _this.SAMPLER3DBGRMAP = false;
  43393. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43394. _this.EXPOSURE = false;
  43395. _this.USEPHYSICALLIGHTFALLOFF = false;
  43396. _this.TWOSIDEDLIGHTING = false;
  43397. _this.SHADOWFLOAT = false;
  43398. _this.CLIPPLANE = false;
  43399. _this.POINTSIZE = false;
  43400. _this.FOG = false;
  43401. _this.LOGARITHMICDEPTH = false;
  43402. _this.FORCENORMALFORWARD = false;
  43403. _this.SPECULARAA = false;
  43404. _this.UNLIT = false;
  43405. _this.rebuild();
  43406. return _this;
  43407. }
  43408. /**
  43409. * Resets the PBR Material defines.
  43410. */
  43411. PBRMaterialDefines.prototype.reset = function () {
  43412. _super.prototype.reset.call(this);
  43413. this.ALPHATESTVALUE = "0.5";
  43414. this.PBR = true;
  43415. };
  43416. return PBRMaterialDefines;
  43417. }(BABYLON.MaterialDefines));
  43418. /**
  43419. * The Physically based material base class of BJS.
  43420. *
  43421. * This offers the main features of a standard PBR material.
  43422. * For more information, please refer to the documentation :
  43423. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43424. */
  43425. var PBRBaseMaterial = /** @class */ (function (_super) {
  43426. __extends(PBRBaseMaterial, _super);
  43427. /**
  43428. * Instantiates a new PBRMaterial instance.
  43429. *
  43430. * @param name The material name
  43431. * @param scene The scene the material will be use in.
  43432. */
  43433. function PBRBaseMaterial(name, scene) {
  43434. var _this = _super.call(this, name, scene) || this;
  43435. /**
  43436. * Intensity of the direct lights e.g. the four lights available in your scene.
  43437. * This impacts both the direct diffuse and specular highlights.
  43438. */
  43439. _this._directIntensity = 1.0;
  43440. /**
  43441. * Intensity of the emissive part of the material.
  43442. * This helps controlling the emissive effect without modifying the emissive color.
  43443. */
  43444. _this._emissiveIntensity = 1.0;
  43445. /**
  43446. * Intensity of the environment e.g. how much the environment will light the object
  43447. * either through harmonics for rough material or through the refelction for shiny ones.
  43448. */
  43449. _this._environmentIntensity = 1.0;
  43450. /**
  43451. * This is a special control allowing the reduction of the specular highlights coming from the
  43452. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43453. */
  43454. _this._specularIntensity = 1.0;
  43455. /**
  43456. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43457. */
  43458. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43459. /**
  43460. * Debug Control allowing disabling the bump map on this material.
  43461. */
  43462. _this._disableBumpMap = false;
  43463. /**
  43464. * AKA Occlusion Texture Intensity in other nomenclature.
  43465. */
  43466. _this._ambientTextureStrength = 1.0;
  43467. /**
  43468. * The color of a material in ambient lighting.
  43469. */
  43470. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43471. /**
  43472. * AKA Diffuse Color in other nomenclature.
  43473. */
  43474. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43475. /**
  43476. * AKA Specular Color in other nomenclature.
  43477. */
  43478. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43479. /**
  43480. * The color applied when light is reflected from a material.
  43481. */
  43482. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43483. /**
  43484. * The color applied when light is emitted from a material.
  43485. */
  43486. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43487. /**
  43488. * AKA Glossiness in other nomenclature.
  43489. */
  43490. _this._microSurface = 0.9;
  43491. /**
  43492. * source material index of refraction (IOR)' / 'destination material IOR.
  43493. */
  43494. _this._indexOfRefraction = 0.66;
  43495. /**
  43496. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43497. */
  43498. _this._invertRefractionY = false;
  43499. /**
  43500. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43501. * Materials half opaque for instance using refraction could benefit from this control.
  43502. */
  43503. _this._linkRefractionWithTransparency = false;
  43504. /**
  43505. * Specifies that the material will use the light map as a show map.
  43506. */
  43507. _this._useLightmapAsShadowmap = false;
  43508. /**
  43509. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43510. * makes the reflect vector face the model (under horizon).
  43511. */
  43512. _this._useHorizonOcclusion = true;
  43513. /**
  43514. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43515. * too much the area relying on ambient texture to define their ambient occlusion.
  43516. */
  43517. _this._useRadianceOcclusion = true;
  43518. /**
  43519. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43520. */
  43521. _this._useAlphaFromAlbedoTexture = false;
  43522. /**
  43523. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43524. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43525. */
  43526. _this._useSpecularOverAlpha = true;
  43527. /**
  43528. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43529. */
  43530. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43531. /**
  43532. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43533. */
  43534. _this._useRoughnessFromMetallicTextureAlpha = true;
  43535. /**
  43536. * Specifies if the metallic texture contains the roughness information in its green channel.
  43537. */
  43538. _this._useRoughnessFromMetallicTextureGreen = false;
  43539. /**
  43540. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43541. */
  43542. _this._useMetallnessFromMetallicTextureBlue = false;
  43543. /**
  43544. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43545. */
  43546. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43547. /**
  43548. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43549. */
  43550. _this._useAmbientInGrayScale = false;
  43551. /**
  43552. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43553. * The material will try to infer what glossiness each pixel should be.
  43554. */
  43555. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43556. /**
  43557. * BJS is using an harcoded light falloff based on a manually sets up range.
  43558. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43559. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43560. */
  43561. _this._usePhysicalLightFalloff = true;
  43562. /**
  43563. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43564. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43565. */
  43566. _this._useRadianceOverAlpha = true;
  43567. /**
  43568. * Allows using an object space normal map (instead of tangent space).
  43569. */
  43570. _this._useObjectSpaceNormalMap = false;
  43571. /**
  43572. * Allows using the bump map in parallax mode.
  43573. */
  43574. _this._useParallax = false;
  43575. /**
  43576. * Allows using the bump map in parallax occlusion mode.
  43577. */
  43578. _this._useParallaxOcclusion = false;
  43579. /**
  43580. * Controls the scale bias of the parallax mode.
  43581. */
  43582. _this._parallaxScaleBias = 0.05;
  43583. /**
  43584. * If sets to true, disables all the lights affecting the material.
  43585. */
  43586. _this._disableLighting = false;
  43587. /**
  43588. * Number of Simultaneous lights allowed on the material.
  43589. */
  43590. _this._maxSimultaneousLights = 4;
  43591. /**
  43592. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43593. */
  43594. _this._invertNormalMapX = false;
  43595. /**
  43596. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43597. */
  43598. _this._invertNormalMapY = false;
  43599. /**
  43600. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43601. */
  43602. _this._twoSidedLighting = false;
  43603. /**
  43604. * Defines the alpha limits in alpha test mode.
  43605. */
  43606. _this._alphaCutOff = 0.4;
  43607. /**
  43608. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43609. */
  43610. _this._forceAlphaTest = false;
  43611. /**
  43612. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43613. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43614. */
  43615. _this._useAlphaFresnel = false;
  43616. /**
  43617. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43618. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43619. */
  43620. _this._useLinearAlphaFresnel = false;
  43621. /**
  43622. * The transparency mode of the material.
  43623. */
  43624. _this._transparencyMode = null;
  43625. /**
  43626. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43627. * from cos thetav and roughness:
  43628. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43629. */
  43630. _this._environmentBRDFTexture = null;
  43631. /**
  43632. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43633. */
  43634. _this._forceIrradianceInFragment = false;
  43635. /**
  43636. * Force normal to face away from face.
  43637. */
  43638. _this._forceNormalForward = false;
  43639. /**
  43640. * Enables specular anti aliasing in the PBR shader.
  43641. * It will both interacts on the Geometry for analytical and IBL lighting.
  43642. * It also prefilter the roughness map based on the bump values.
  43643. */
  43644. _this._enableSpecularAntiAliasing = false;
  43645. /**
  43646. * Stores the available render targets.
  43647. */
  43648. _this._renderTargets = new BABYLON.SmartArray(16);
  43649. /**
  43650. * Sets the global ambient color for the material used in lighting calculations.
  43651. */
  43652. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43653. /**
  43654. * If set to true, no lighting calculations will be applied.
  43655. */
  43656. _this._unlit = false;
  43657. // Setup the default processing configuration to the scene.
  43658. _this._attachImageProcessingConfiguration(null);
  43659. _this.getRenderTargetTextures = function () {
  43660. _this._renderTargets.reset();
  43661. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43662. _this._renderTargets.push(_this._reflectionTexture);
  43663. }
  43664. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43665. _this._renderTargets.push(_this._refractionTexture);
  43666. }
  43667. return _this._renderTargets;
  43668. };
  43669. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43670. return _this;
  43671. }
  43672. /**
  43673. * Attaches a new image processing configuration to the PBR Material.
  43674. * @param configuration
  43675. */
  43676. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43677. var _this = this;
  43678. if (configuration === this._imageProcessingConfiguration) {
  43679. return;
  43680. }
  43681. // Detaches observer.
  43682. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43683. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43684. }
  43685. // Pick the scene configuration if needed.
  43686. if (!configuration) {
  43687. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43688. }
  43689. else {
  43690. this._imageProcessingConfiguration = configuration;
  43691. }
  43692. // Attaches observer.
  43693. if (this._imageProcessingConfiguration) {
  43694. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43695. _this._markAllSubMeshesAsImageProcessingDirty();
  43696. });
  43697. }
  43698. };
  43699. /**
  43700. * Gets the name of the material class.
  43701. */
  43702. PBRBaseMaterial.prototype.getClassName = function () {
  43703. return "PBRBaseMaterial";
  43704. };
  43705. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43706. /**
  43707. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43708. */
  43709. get: function () {
  43710. return this._useLogarithmicDepth;
  43711. },
  43712. /**
  43713. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43714. */
  43715. set: function (value) {
  43716. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43717. },
  43718. enumerable: true,
  43719. configurable: true
  43720. });
  43721. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43722. /**
  43723. * Gets the current transparency mode.
  43724. */
  43725. get: function () {
  43726. return this._transparencyMode;
  43727. },
  43728. /**
  43729. * Sets the transparency mode of the material.
  43730. *
  43731. * | Value | Type | Description |
  43732. * | ----- | ----------------------------------- | ----------- |
  43733. * | 0 | OPAQUE | |
  43734. * | 1 | ALPHATEST | |
  43735. * | 2 | ALPHABLEND | |
  43736. * | 3 | ALPHATESTANDBLEND | |
  43737. *
  43738. */
  43739. set: function (value) {
  43740. if (this._transparencyMode === value) {
  43741. return;
  43742. }
  43743. this._transparencyMode = value;
  43744. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43745. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43746. },
  43747. enumerable: true,
  43748. configurable: true
  43749. });
  43750. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43751. /**
  43752. * Returns true if alpha blending should be disabled.
  43753. */
  43754. get: function () {
  43755. return (this._linkRefractionWithTransparency ||
  43756. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43757. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43758. },
  43759. enumerable: true,
  43760. configurable: true
  43761. });
  43762. /**
  43763. * Specifies whether or not this material should be rendered in alpha blend mode.
  43764. */
  43765. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43766. if (this._disableAlphaBlending) {
  43767. return false;
  43768. }
  43769. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43770. };
  43771. /**
  43772. * Specifies if the mesh will require alpha blending.
  43773. * @param mesh - BJS mesh.
  43774. */
  43775. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43776. if (this._disableAlphaBlending) {
  43777. return false;
  43778. }
  43779. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43780. };
  43781. /**
  43782. * Specifies whether or not this material should be rendered in alpha test mode.
  43783. */
  43784. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43785. if (this._forceAlphaTest) {
  43786. return true;
  43787. }
  43788. if (this._linkRefractionWithTransparency) {
  43789. return false;
  43790. }
  43791. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43792. };
  43793. /**
  43794. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43795. */
  43796. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43797. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43798. };
  43799. /**
  43800. * Gets the texture used for the alpha test.
  43801. */
  43802. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43803. return this._albedoTexture;
  43804. };
  43805. /**
  43806. * Specifies that the submesh is ready to be used.
  43807. * @param mesh - BJS mesh.
  43808. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43809. * @param useInstances - Specifies that instances should be used.
  43810. * @returns - boolean indicating that the submesh is ready or not.
  43811. */
  43812. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43813. if (subMesh.effect && this.isFrozen) {
  43814. if (this._wasPreviouslyReady) {
  43815. return true;
  43816. }
  43817. }
  43818. if (!subMesh._materialDefines) {
  43819. subMesh._materialDefines = new PBRMaterialDefines();
  43820. }
  43821. var defines = subMesh._materialDefines;
  43822. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43823. if (defines._renderId === this.getScene().getRenderId()) {
  43824. return true;
  43825. }
  43826. }
  43827. var scene = this.getScene();
  43828. var engine = scene.getEngine();
  43829. if (defines._areTexturesDirty) {
  43830. if (scene.texturesEnabled) {
  43831. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43832. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43833. return false;
  43834. }
  43835. }
  43836. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43837. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43838. return false;
  43839. }
  43840. }
  43841. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43842. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43843. return false;
  43844. }
  43845. }
  43846. var reflectionTexture = this._getReflectionTexture();
  43847. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43848. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43849. return false;
  43850. }
  43851. }
  43852. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43853. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43854. return false;
  43855. }
  43856. }
  43857. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43858. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43859. return false;
  43860. }
  43861. }
  43862. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43863. if (this._metallicTexture) {
  43864. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43865. return false;
  43866. }
  43867. }
  43868. else if (this._reflectivityTexture) {
  43869. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43870. return false;
  43871. }
  43872. }
  43873. if (this._microSurfaceTexture) {
  43874. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43875. return false;
  43876. }
  43877. }
  43878. }
  43879. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43880. // Bump texture cannot be not blocking.
  43881. if (!this._bumpTexture.isReady()) {
  43882. return false;
  43883. }
  43884. }
  43885. var refractionTexture = this._getRefractionTexture();
  43886. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43887. if (!refractionTexture.isReadyOrNotBlocking()) {
  43888. return false;
  43889. }
  43890. }
  43891. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43892. // This is blocking.
  43893. if (!this._environmentBRDFTexture.isReady()) {
  43894. return false;
  43895. }
  43896. }
  43897. }
  43898. }
  43899. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43900. if (!this._imageProcessingConfiguration.isReady()) {
  43901. return false;
  43902. }
  43903. }
  43904. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43905. mesh.createNormals(true);
  43906. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43907. }
  43908. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43909. if (effect) {
  43910. scene.resetCachedMaterial();
  43911. subMesh.setEffect(effect, defines);
  43912. this.buildUniformLayout();
  43913. }
  43914. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43915. return false;
  43916. }
  43917. defines._renderId = scene.getRenderId();
  43918. this._wasPreviouslyReady = true;
  43919. return true;
  43920. };
  43921. /**
  43922. * Specifies if the material uses metallic roughness workflow.
  43923. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43924. */
  43925. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43926. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43927. return true;
  43928. }
  43929. return false;
  43930. };
  43931. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43932. if (onCompiled === void 0) { onCompiled = null; }
  43933. if (onError === void 0) { onError = null; }
  43934. if (useInstances === void 0) { useInstances = null; }
  43935. if (useClipPlane === void 0) { useClipPlane = null; }
  43936. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43937. if (!defines.isDirty) {
  43938. return null;
  43939. }
  43940. defines.markAsProcessed();
  43941. var scene = this.getScene();
  43942. var engine = scene.getEngine();
  43943. // Fallbacks
  43944. var fallbacks = new BABYLON.EffectFallbacks();
  43945. var fallbackRank = 0;
  43946. if (defines.USESPHERICALINVERTEX) {
  43947. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43948. }
  43949. if (defines.FOG) {
  43950. fallbacks.addFallback(fallbackRank, "FOG");
  43951. }
  43952. if (defines.SPECULARAA) {
  43953. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43954. }
  43955. if (defines.POINTSIZE) {
  43956. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43957. }
  43958. if (defines.LOGARITHMICDEPTH) {
  43959. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43960. }
  43961. if (defines.PARALLAX) {
  43962. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43963. }
  43964. if (defines.PARALLAXOCCLUSION) {
  43965. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43966. }
  43967. if (defines.ENVIRONMENTBRDF) {
  43968. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43969. }
  43970. if (defines.TANGENT) {
  43971. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43972. }
  43973. if (defines.BUMP) {
  43974. fallbacks.addFallback(fallbackRank++, "BUMP");
  43975. }
  43976. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43977. if (defines.SPECULARTERM) {
  43978. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43979. }
  43980. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43981. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43982. }
  43983. if (defines.LIGHTMAP) {
  43984. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43985. }
  43986. if (defines.NORMAL) {
  43987. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43988. }
  43989. if (defines.AMBIENT) {
  43990. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43991. }
  43992. if (defines.EMISSIVE) {
  43993. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43994. }
  43995. if (defines.VERTEXCOLOR) {
  43996. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43997. }
  43998. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43999. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44000. }
  44001. if (defines.MORPHTARGETS) {
  44002. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44003. }
  44004. //Attributes
  44005. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44006. if (defines.NORMAL) {
  44007. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44008. }
  44009. if (defines.TANGENT) {
  44010. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44011. }
  44012. if (defines.UV1) {
  44013. attribs.push(BABYLON.VertexBuffer.UVKind);
  44014. }
  44015. if (defines.UV2) {
  44016. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44017. }
  44018. if (defines.VERTEXCOLOR) {
  44019. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44020. }
  44021. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44022. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44023. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44024. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44025. "vFogInfos", "vFogColor", "pointSize",
  44026. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44027. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44028. "mBones",
  44029. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44030. "vLightingIntensity",
  44031. "logarithmicDepthConstant",
  44032. "vSphericalX", "vSphericalY", "vSphericalZ",
  44033. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44034. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44035. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44036. "vTangentSpaceParams"
  44037. ];
  44038. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44039. "bumpSampler", "lightmapSampler", "opacitySampler",
  44040. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44041. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44042. "microSurfaceSampler", "environmentBrdfSampler"];
  44043. var uniformBuffers = ["Material", "Scene"];
  44044. if (BABYLON.ImageProcessingConfiguration) {
  44045. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44046. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44047. }
  44048. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44049. uniformsNames: uniforms,
  44050. uniformBuffersNames: uniformBuffers,
  44051. samplers: samplers,
  44052. defines: defines,
  44053. maxSimultaneousLights: this._maxSimultaneousLights
  44054. });
  44055. var join = defines.toString();
  44056. return engine.createEffect("pbr", {
  44057. attributes: attribs,
  44058. uniformsNames: uniforms,
  44059. uniformBuffersNames: uniformBuffers,
  44060. samplers: samplers,
  44061. defines: join,
  44062. fallbacks: fallbacks,
  44063. onCompiled: onCompiled,
  44064. onError: onError,
  44065. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44066. }, engine);
  44067. };
  44068. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44069. if (useInstances === void 0) { useInstances = null; }
  44070. if (useClipPlane === void 0) { useClipPlane = null; }
  44071. var scene = this.getScene();
  44072. var engine = scene.getEngine();
  44073. // Lights
  44074. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44075. defines._needNormals = true;
  44076. // Textures
  44077. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44078. if (defines._areTexturesDirty) {
  44079. defines._needUVs = false;
  44080. if (scene.texturesEnabled) {
  44081. if (scene.getEngine().getCaps().textureLOD) {
  44082. defines.LODBASEDMICROSFURACE = true;
  44083. }
  44084. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44085. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44086. }
  44087. else {
  44088. defines.ALBEDO = false;
  44089. }
  44090. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44091. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44092. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44093. }
  44094. else {
  44095. defines.AMBIENT = false;
  44096. }
  44097. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44098. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44099. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44100. }
  44101. else {
  44102. defines.OPACITY = false;
  44103. }
  44104. var reflectionTexture = this._getReflectionTexture();
  44105. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44106. defines.REFLECTION = true;
  44107. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44108. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44109. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44110. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44111. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44112. defines.INVERTCUBICMAP = true;
  44113. }
  44114. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44115. switch (reflectionTexture.coordinatesMode) {
  44116. case BABYLON.Texture.EXPLICIT_MODE:
  44117. defines.REFLECTIONMAP_EXPLICIT = true;
  44118. break;
  44119. case BABYLON.Texture.PLANAR_MODE:
  44120. defines.REFLECTIONMAP_PLANAR = true;
  44121. break;
  44122. case BABYLON.Texture.PROJECTION_MODE:
  44123. defines.REFLECTIONMAP_PROJECTION = true;
  44124. break;
  44125. case BABYLON.Texture.SKYBOX_MODE:
  44126. defines.REFLECTIONMAP_SKYBOX = true;
  44127. break;
  44128. case BABYLON.Texture.SPHERICAL_MODE:
  44129. defines.REFLECTIONMAP_SPHERICAL = true;
  44130. break;
  44131. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44132. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44133. break;
  44134. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44135. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44136. break;
  44137. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44138. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44139. break;
  44140. case BABYLON.Texture.CUBIC_MODE:
  44141. case BABYLON.Texture.INVCUBIC_MODE:
  44142. default:
  44143. defines.REFLECTIONMAP_CUBIC = true;
  44144. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44145. break;
  44146. }
  44147. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44148. if (reflectionTexture.sphericalPolynomial) {
  44149. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44150. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44151. defines.USESPHERICALINVERTEX = false;
  44152. }
  44153. else {
  44154. defines.USESPHERICALINVERTEX = true;
  44155. }
  44156. }
  44157. }
  44158. }
  44159. else {
  44160. defines.REFLECTION = false;
  44161. defines.REFLECTIONMAP_3D = false;
  44162. defines.REFLECTIONMAP_SPHERICAL = false;
  44163. defines.REFLECTIONMAP_PLANAR = false;
  44164. defines.REFLECTIONMAP_CUBIC = false;
  44165. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44166. defines.REFLECTIONMAP_PROJECTION = false;
  44167. defines.REFLECTIONMAP_SKYBOX = false;
  44168. defines.REFLECTIONMAP_EXPLICIT = false;
  44169. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44170. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44171. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44172. defines.INVERTCUBICMAP = false;
  44173. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44174. defines.USESPHERICALINVERTEX = false;
  44175. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44176. defines.LODINREFLECTIONALPHA = false;
  44177. defines.GAMMAREFLECTION = false;
  44178. defines.RGBDREFLECTION = false;
  44179. }
  44180. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44181. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44182. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44183. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44184. }
  44185. else {
  44186. defines.LIGHTMAP = false;
  44187. }
  44188. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44189. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44190. }
  44191. else {
  44192. defines.EMISSIVE = false;
  44193. }
  44194. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44195. if (this._metallicTexture) {
  44196. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44197. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44198. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44199. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44200. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44201. }
  44202. else if (this._reflectivityTexture) {
  44203. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44204. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44205. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44206. }
  44207. else {
  44208. defines.REFLECTIVITY = false;
  44209. }
  44210. if (this._microSurfaceTexture) {
  44211. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44212. }
  44213. else {
  44214. defines.MICROSURFACEMAP = false;
  44215. }
  44216. }
  44217. else {
  44218. defines.REFLECTIVITY = false;
  44219. defines.MICROSURFACEMAP = false;
  44220. }
  44221. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44222. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44223. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44224. defines.PARALLAX = true;
  44225. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44226. }
  44227. else {
  44228. defines.PARALLAX = false;
  44229. }
  44230. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44231. }
  44232. else {
  44233. defines.BUMP = false;
  44234. }
  44235. var refractionTexture = this._getRefractionTexture();
  44236. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44237. defines.REFRACTION = true;
  44238. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44239. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44240. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44241. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44242. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44243. if (this._linkRefractionWithTransparency) {
  44244. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44245. }
  44246. }
  44247. else {
  44248. defines.REFRACTION = false;
  44249. }
  44250. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44251. defines.ENVIRONMENTBRDF = true;
  44252. }
  44253. else {
  44254. defines.ENVIRONMENTBRDF = false;
  44255. }
  44256. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44257. defines.ALPHAFROMALBEDO = true;
  44258. }
  44259. else {
  44260. defines.ALPHAFROMALBEDO = false;
  44261. }
  44262. }
  44263. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44264. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44265. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44266. if (!this.backFaceCulling && this._twoSidedLighting) {
  44267. defines.TWOSIDEDLIGHTING = true;
  44268. }
  44269. else {
  44270. defines.TWOSIDEDLIGHTING = false;
  44271. }
  44272. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44273. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44274. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44275. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44276. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44277. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44278. }
  44279. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44280. this._imageProcessingConfiguration.prepareDefines(defines);
  44281. }
  44282. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44283. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44284. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44285. // Misc.
  44286. if (defines._areMiscDirty) {
  44287. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44288. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44289. }
  44290. // Values that need to be evaluated on every frame
  44291. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44292. // Attribs
  44293. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44294. };
  44295. /**
  44296. * Force shader compilation
  44297. */
  44298. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44299. var _this = this;
  44300. var localOptions = __assign({ clipPlane: false }, options);
  44301. var defines = new PBRMaterialDefines();
  44302. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44303. if (effect.isReady()) {
  44304. if (onCompiled) {
  44305. onCompiled(this);
  44306. }
  44307. }
  44308. else {
  44309. effect.onCompileObservable.add(function () {
  44310. if (onCompiled) {
  44311. onCompiled(_this);
  44312. }
  44313. });
  44314. }
  44315. };
  44316. /**
  44317. * Initializes the uniform buffer layout for the shader.
  44318. */
  44319. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44320. // Order is important !
  44321. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44322. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44323. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44324. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44325. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44326. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44327. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44328. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44329. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44330. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44331. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44332. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44333. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44334. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44335. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44336. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44337. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44338. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44339. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44340. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44341. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44342. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44343. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44344. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44345. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44346. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44347. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44348. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44349. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44350. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44351. this._uniformBuffer.addUniform("pointSize", 1);
  44352. this._uniformBuffer.create();
  44353. };
  44354. /**
  44355. * Unbinds the textures.
  44356. */
  44357. PBRBaseMaterial.prototype.unbind = function () {
  44358. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44359. this._uniformBuffer.setTexture("reflectionSampler", null);
  44360. }
  44361. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44362. this._uniformBuffer.setTexture("refractionSampler", null);
  44363. }
  44364. _super.prototype.unbind.call(this);
  44365. };
  44366. /**
  44367. * Binds the submesh data.
  44368. * @param world - The world matrix.
  44369. * @param mesh - The BJS mesh.
  44370. * @param subMesh - A submesh of the BJS mesh.
  44371. */
  44372. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44373. var scene = this.getScene();
  44374. var defines = subMesh._materialDefines;
  44375. if (!defines) {
  44376. return;
  44377. }
  44378. var effect = subMesh.effect;
  44379. if (!effect) {
  44380. return;
  44381. }
  44382. this._activeEffect = effect;
  44383. // Matrices
  44384. this.bindOnlyWorldMatrix(world);
  44385. // Normal Matrix
  44386. if (defines.OBJECTSPACE_NORMALMAP) {
  44387. world.toNormalMatrix(this._normalMatrix);
  44388. this.bindOnlyNormalMatrix(this._normalMatrix);
  44389. }
  44390. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44391. // Bones
  44392. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44393. var reflectionTexture = null;
  44394. if (mustRebind) {
  44395. this._uniformBuffer.bindToEffect(effect, "Material");
  44396. this.bindViewProjection(effect);
  44397. reflectionTexture = this._getReflectionTexture();
  44398. var refractionTexture = this._getRefractionTexture();
  44399. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44400. // Texture uniforms
  44401. if (scene.texturesEnabled) {
  44402. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44403. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44404. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44405. }
  44406. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44407. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44408. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44409. }
  44410. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44411. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44412. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44413. }
  44414. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44415. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44416. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44417. if (reflectionTexture.boundingBoxSize) {
  44418. var cubeTexture = reflectionTexture;
  44419. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44420. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44421. }
  44422. var polynomials = reflectionTexture.sphericalPolynomial;
  44423. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44424. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44425. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44426. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44427. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44428. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44429. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44430. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44431. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44432. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44433. }
  44434. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44435. }
  44436. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44437. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44438. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44439. }
  44440. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44441. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44442. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44443. }
  44444. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44445. if (this._metallicTexture) {
  44446. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44447. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44448. }
  44449. else if (this._reflectivityTexture) {
  44450. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44451. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44452. }
  44453. if (this._microSurfaceTexture) {
  44454. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44455. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44456. }
  44457. }
  44458. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44459. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44460. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44461. if (scene._mirroredCameraPosition) {
  44462. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44463. }
  44464. else {
  44465. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44466. }
  44467. }
  44468. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44469. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44470. var depth = 1.0;
  44471. if (!refractionTexture.isCube) {
  44472. if (refractionTexture.depth) {
  44473. depth = refractionTexture.depth;
  44474. }
  44475. }
  44476. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44477. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44478. }
  44479. }
  44480. // Point size
  44481. if (this.pointsCloud) {
  44482. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44483. }
  44484. // Colors
  44485. if (defines.METALLICWORKFLOW) {
  44486. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44487. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44488. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44489. }
  44490. else {
  44491. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44492. }
  44493. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44494. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44495. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44496. // Misc
  44497. this._lightingInfos.x = this._directIntensity;
  44498. this._lightingInfos.y = this._emissiveIntensity;
  44499. this._lightingInfos.z = this._environmentIntensity;
  44500. this._lightingInfos.w = this._specularIntensity;
  44501. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44502. }
  44503. // Textures
  44504. if (scene.texturesEnabled) {
  44505. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44506. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44507. }
  44508. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44509. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44510. }
  44511. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44512. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44513. }
  44514. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44515. if (defines.LODBASEDMICROSFURACE) {
  44516. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44517. }
  44518. else {
  44519. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44520. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44521. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44522. }
  44523. }
  44524. if (defines.ENVIRONMENTBRDF) {
  44525. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44526. }
  44527. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44528. if (defines.LODBASEDMICROSFURACE) {
  44529. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44530. }
  44531. else {
  44532. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44533. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44534. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44535. }
  44536. }
  44537. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44538. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44539. }
  44540. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44541. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44542. }
  44543. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44544. if (this._metallicTexture) {
  44545. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44546. }
  44547. else if (this._reflectivityTexture) {
  44548. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44549. }
  44550. if (this._microSurfaceTexture) {
  44551. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44552. }
  44553. }
  44554. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44555. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44556. }
  44557. }
  44558. // Clip plane
  44559. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44560. // Colors
  44561. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44562. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44563. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44564. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44565. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44566. }
  44567. if (mustRebind || !this.isFrozen) {
  44568. // Lights
  44569. if (scene.lightsEnabled && !this._disableLighting) {
  44570. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44571. }
  44572. // View
  44573. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44574. this.bindView(effect);
  44575. }
  44576. // Fog
  44577. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44578. // Morph targets
  44579. if (defines.NUM_MORPH_INFLUENCERS) {
  44580. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44581. }
  44582. // image processing
  44583. this._imageProcessingConfiguration.bind(this._activeEffect);
  44584. // Log. depth
  44585. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44586. }
  44587. this._uniformBuffer.update();
  44588. this._afterBind(mesh, this._activeEffect);
  44589. };
  44590. /**
  44591. * Returns the animatable textures.
  44592. * @returns - Array of animatable textures.
  44593. */
  44594. PBRBaseMaterial.prototype.getAnimatables = function () {
  44595. var results = [];
  44596. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44597. results.push(this._albedoTexture);
  44598. }
  44599. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44600. results.push(this._ambientTexture);
  44601. }
  44602. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44603. results.push(this._opacityTexture);
  44604. }
  44605. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44606. results.push(this._reflectionTexture);
  44607. }
  44608. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44609. results.push(this._emissiveTexture);
  44610. }
  44611. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44612. results.push(this._metallicTexture);
  44613. }
  44614. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44615. results.push(this._reflectivityTexture);
  44616. }
  44617. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44618. results.push(this._bumpTexture);
  44619. }
  44620. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44621. results.push(this._lightmapTexture);
  44622. }
  44623. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44624. results.push(this._refractionTexture);
  44625. }
  44626. return results;
  44627. };
  44628. /**
  44629. * Returns the texture used for reflections.
  44630. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44631. */
  44632. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44633. if (this._reflectionTexture) {
  44634. return this._reflectionTexture;
  44635. }
  44636. return this.getScene().environmentTexture;
  44637. };
  44638. /**
  44639. * Returns the texture used for refraction or null if none is used.
  44640. * @returns - Refection texture if present. If no refraction texture and refraction
  44641. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44642. */
  44643. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44644. if (this._refractionTexture) {
  44645. return this._refractionTexture;
  44646. }
  44647. if (this._linkRefractionWithTransparency) {
  44648. return this.getScene().environmentTexture;
  44649. }
  44650. return null;
  44651. };
  44652. /**
  44653. * Disposes the resources of the material.
  44654. * @param forceDisposeEffect - Forces the disposal of effects.
  44655. * @param forceDisposeTextures - Forces the disposal of all textures.
  44656. */
  44657. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44658. if (forceDisposeTextures) {
  44659. if (this._albedoTexture) {
  44660. this._albedoTexture.dispose();
  44661. }
  44662. if (this._ambientTexture) {
  44663. this._ambientTexture.dispose();
  44664. }
  44665. if (this._opacityTexture) {
  44666. this._opacityTexture.dispose();
  44667. }
  44668. if (this._reflectionTexture) {
  44669. this._reflectionTexture.dispose();
  44670. }
  44671. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44672. this._environmentBRDFTexture.dispose();
  44673. }
  44674. if (this._emissiveTexture) {
  44675. this._emissiveTexture.dispose();
  44676. }
  44677. if (this._metallicTexture) {
  44678. this._metallicTexture.dispose();
  44679. }
  44680. if (this._reflectivityTexture) {
  44681. this._reflectivityTexture.dispose();
  44682. }
  44683. if (this._bumpTexture) {
  44684. this._bumpTexture.dispose();
  44685. }
  44686. if (this._lightmapTexture) {
  44687. this._lightmapTexture.dispose();
  44688. }
  44689. if (this._refractionTexture) {
  44690. this._refractionTexture.dispose();
  44691. }
  44692. }
  44693. this._renderTargets.dispose();
  44694. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44695. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44696. }
  44697. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44698. };
  44699. /**
  44700. * Stores the reflectivity values based on metallic roughness workflow.
  44701. */
  44702. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44703. __decorate([
  44704. BABYLON.serializeAsImageProcessingConfiguration()
  44705. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44706. __decorate([
  44707. BABYLON.serialize()
  44708. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44709. __decorate([
  44710. BABYLON.serialize()
  44711. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44712. return PBRBaseMaterial;
  44713. }(BABYLON.PushMaterial));
  44714. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44715. })(BABYLON || (BABYLON = {}));
  44716. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44717. var BABYLON;
  44718. (function (BABYLON) {
  44719. /**
  44720. * The Physically based simple base material of BJS.
  44721. *
  44722. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44723. * It is used as the base class for both the specGloss and metalRough conventions.
  44724. */
  44725. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44726. __extends(PBRBaseSimpleMaterial, _super);
  44727. /**
  44728. * Instantiates a new PBRMaterial instance.
  44729. *
  44730. * @param name The material name
  44731. * @param scene The scene the material will be use in.
  44732. */
  44733. function PBRBaseSimpleMaterial(name, scene) {
  44734. var _this = _super.call(this, name, scene) || this;
  44735. /**
  44736. * Number of Simultaneous lights allowed on the material.
  44737. */
  44738. _this.maxSimultaneousLights = 4;
  44739. /**
  44740. * If sets to true, disables all the lights affecting the material.
  44741. */
  44742. _this.disableLighting = false;
  44743. /**
  44744. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44745. */
  44746. _this.invertNormalMapX = false;
  44747. /**
  44748. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44749. */
  44750. _this.invertNormalMapY = false;
  44751. /**
  44752. * Emissivie color used to self-illuminate the model.
  44753. */
  44754. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44755. /**
  44756. * Occlusion Channel Strenght.
  44757. */
  44758. _this.occlusionStrength = 1.0;
  44759. _this.useLightmapAsShadowmap = false;
  44760. _this._useAlphaFromAlbedoTexture = true;
  44761. _this._useAmbientInGrayScale = true;
  44762. return _this;
  44763. }
  44764. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44765. /**
  44766. * Gets the current double sided mode.
  44767. */
  44768. get: function () {
  44769. return this._twoSidedLighting;
  44770. },
  44771. /**
  44772. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44773. */
  44774. set: function (value) {
  44775. if (this._twoSidedLighting === value) {
  44776. return;
  44777. }
  44778. this._twoSidedLighting = value;
  44779. this.backFaceCulling = !value;
  44780. this._markAllSubMeshesAsTexturesDirty();
  44781. },
  44782. enumerable: true,
  44783. configurable: true
  44784. });
  44785. /**
  44786. * Return the active textures of the material.
  44787. */
  44788. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44789. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44790. if (this.environmentTexture) {
  44791. activeTextures.push(this.environmentTexture);
  44792. }
  44793. if (this.normalTexture) {
  44794. activeTextures.push(this.normalTexture);
  44795. }
  44796. if (this.emissiveTexture) {
  44797. activeTextures.push(this.emissiveTexture);
  44798. }
  44799. if (this.occlusionTexture) {
  44800. activeTextures.push(this.occlusionTexture);
  44801. }
  44802. if (this.lightmapTexture) {
  44803. activeTextures.push(this.lightmapTexture);
  44804. }
  44805. return activeTextures;
  44806. };
  44807. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44808. if (_super.prototype.hasTexture.call(this, texture)) {
  44809. return true;
  44810. }
  44811. if (this.lightmapTexture === texture) {
  44812. return true;
  44813. }
  44814. return false;
  44815. };
  44816. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44817. return "PBRBaseSimpleMaterial";
  44818. };
  44819. __decorate([
  44820. BABYLON.serialize(),
  44821. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44822. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44823. __decorate([
  44824. BABYLON.serialize(),
  44825. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44826. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44827. __decorate([
  44828. BABYLON.serializeAsTexture(),
  44829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44830. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44831. __decorate([
  44832. BABYLON.serialize(),
  44833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44834. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44835. __decorate([
  44836. BABYLON.serialize(),
  44837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44838. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44839. __decorate([
  44840. BABYLON.serializeAsTexture(),
  44841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44842. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44843. __decorate([
  44844. BABYLON.serializeAsColor3("emissive"),
  44845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44846. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44847. __decorate([
  44848. BABYLON.serializeAsTexture(),
  44849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44850. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44851. __decorate([
  44852. BABYLON.serialize(),
  44853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44854. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44855. __decorate([
  44856. BABYLON.serializeAsTexture(),
  44857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44858. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44859. __decorate([
  44860. BABYLON.serialize(),
  44861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44862. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44863. __decorate([
  44864. BABYLON.serialize()
  44865. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44866. __decorate([
  44867. BABYLON.serializeAsTexture(),
  44868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44869. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44870. __decorate([
  44871. BABYLON.serialize(),
  44872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44873. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44874. return PBRBaseSimpleMaterial;
  44875. }(BABYLON.PBRBaseMaterial));
  44876. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44877. })(BABYLON || (BABYLON = {}));
  44878. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44879. var BABYLON;
  44880. (function (BABYLON) {
  44881. /**
  44882. * The Physically based material of BJS.
  44883. *
  44884. * This offers the main features of a standard PBR material.
  44885. * For more information, please refer to the documentation :
  44886. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44887. */
  44888. var PBRMaterial = /** @class */ (function (_super) {
  44889. __extends(PBRMaterial, _super);
  44890. /**
  44891. * Instantiates a new PBRMaterial instance.
  44892. *
  44893. * @param name The material name
  44894. * @param scene The scene the material will be use in.
  44895. */
  44896. function PBRMaterial(name, scene) {
  44897. var _this = _super.call(this, name, scene) || this;
  44898. /**
  44899. * Intensity of the direct lights e.g. the four lights available in your scene.
  44900. * This impacts both the direct diffuse and specular highlights.
  44901. */
  44902. _this.directIntensity = 1.0;
  44903. /**
  44904. * Intensity of the emissive part of the material.
  44905. * This helps controlling the emissive effect without modifying the emissive color.
  44906. */
  44907. _this.emissiveIntensity = 1.0;
  44908. /**
  44909. * Intensity of the environment e.g. how much the environment will light the object
  44910. * either through harmonics for rough material or through the refelction for shiny ones.
  44911. */
  44912. _this.environmentIntensity = 1.0;
  44913. /**
  44914. * This is a special control allowing the reduction of the specular highlights coming from the
  44915. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44916. */
  44917. _this.specularIntensity = 1.0;
  44918. /**
  44919. * Debug Control allowing disabling the bump map on this material.
  44920. */
  44921. _this.disableBumpMap = false;
  44922. /**
  44923. * AKA Occlusion Texture Intensity in other nomenclature.
  44924. */
  44925. _this.ambientTextureStrength = 1.0;
  44926. /**
  44927. * The color of a material in ambient lighting.
  44928. */
  44929. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44930. /**
  44931. * AKA Diffuse Color in other nomenclature.
  44932. */
  44933. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44934. /**
  44935. * AKA Specular Color in other nomenclature.
  44936. */
  44937. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44938. /**
  44939. * The color reflected from the material.
  44940. */
  44941. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44942. /**
  44943. * The color emitted from the material.
  44944. */
  44945. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44946. /**
  44947. * AKA Glossiness in other nomenclature.
  44948. */
  44949. _this.microSurface = 1.0;
  44950. /**
  44951. * source material index of refraction (IOR)' / 'destination material IOR.
  44952. */
  44953. _this.indexOfRefraction = 0.66;
  44954. /**
  44955. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44956. */
  44957. _this.invertRefractionY = false;
  44958. /**
  44959. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44960. * Materials half opaque for instance using refraction could benefit from this control.
  44961. */
  44962. _this.linkRefractionWithTransparency = false;
  44963. _this.useLightmapAsShadowmap = false;
  44964. /**
  44965. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44966. */
  44967. _this.useAlphaFromAlbedoTexture = false;
  44968. /**
  44969. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44970. */
  44971. _this.forceAlphaTest = false;
  44972. /**
  44973. * Defines the alpha limits in alpha test mode.
  44974. */
  44975. _this.alphaCutOff = 0.4;
  44976. /**
  44977. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44978. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44979. */
  44980. _this.useSpecularOverAlpha = true;
  44981. /**
  44982. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44983. */
  44984. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44985. /**
  44986. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44987. */
  44988. _this.useRoughnessFromMetallicTextureAlpha = true;
  44989. /**
  44990. * Specifies if the metallic texture contains the roughness information in its green channel.
  44991. */
  44992. _this.useRoughnessFromMetallicTextureGreen = false;
  44993. /**
  44994. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44995. */
  44996. _this.useMetallnessFromMetallicTextureBlue = false;
  44997. /**
  44998. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44999. */
  45000. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45001. /**
  45002. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45003. */
  45004. _this.useAmbientInGrayScale = false;
  45005. /**
  45006. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45007. * The material will try to infer what glossiness each pixel should be.
  45008. */
  45009. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45010. /**
  45011. * BJS is using an harcoded light falloff based on a manually sets up range.
  45012. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45013. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45014. */
  45015. _this.usePhysicalLightFalloff = true;
  45016. /**
  45017. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45018. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45019. */
  45020. _this.useRadianceOverAlpha = true;
  45021. /**
  45022. * Allows using an object space normal map (instead of tangent space).
  45023. */
  45024. _this.useObjectSpaceNormalMap = false;
  45025. /**
  45026. * Allows using the bump map in parallax mode.
  45027. */
  45028. _this.useParallax = false;
  45029. /**
  45030. * Allows using the bump map in parallax occlusion mode.
  45031. */
  45032. _this.useParallaxOcclusion = false;
  45033. /**
  45034. * Controls the scale bias of the parallax mode.
  45035. */
  45036. _this.parallaxScaleBias = 0.05;
  45037. /**
  45038. * If sets to true, disables all the lights affecting the material.
  45039. */
  45040. _this.disableLighting = false;
  45041. /**
  45042. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45043. */
  45044. _this.forceIrradianceInFragment = false;
  45045. /**
  45046. * Number of Simultaneous lights allowed on the material.
  45047. */
  45048. _this.maxSimultaneousLights = 4;
  45049. /**
  45050. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45051. */
  45052. _this.invertNormalMapX = false;
  45053. /**
  45054. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45055. */
  45056. _this.invertNormalMapY = false;
  45057. /**
  45058. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45059. */
  45060. _this.twoSidedLighting = false;
  45061. /**
  45062. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45063. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45064. */
  45065. _this.useAlphaFresnel = false;
  45066. /**
  45067. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45068. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45069. */
  45070. _this.useLinearAlphaFresnel = false;
  45071. /**
  45072. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45073. * And/Or occlude the blended part.
  45074. */
  45075. _this.environmentBRDFTexture = null;
  45076. /**
  45077. * Force normal to face away from face.
  45078. */
  45079. _this.forceNormalForward = false;
  45080. /**
  45081. * Enables specular anti aliasing in the PBR shader.
  45082. * It will both interacts on the Geometry for analytical and IBL lighting.
  45083. * It also prefilter the roughness map based on the bump values.
  45084. */
  45085. _this.enableSpecularAntiAliasing = false;
  45086. /**
  45087. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45088. * makes the reflect vector face the model (under horizon).
  45089. */
  45090. _this.useHorizonOcclusion = true;
  45091. /**
  45092. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45093. * too much the area relying on ambient texture to define their ambient occlusion.
  45094. */
  45095. _this.useRadianceOcclusion = true;
  45096. /**
  45097. * If set to true, no lighting calculations will be applied.
  45098. */
  45099. _this.unlit = false;
  45100. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45101. return _this;
  45102. }
  45103. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45104. /**
  45105. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45106. */
  45107. get: function () {
  45108. return this._PBRMATERIAL_OPAQUE;
  45109. },
  45110. enumerable: true,
  45111. configurable: true
  45112. });
  45113. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45114. /**
  45115. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45116. */
  45117. get: function () {
  45118. return this._PBRMATERIAL_ALPHATEST;
  45119. },
  45120. enumerable: true,
  45121. configurable: true
  45122. });
  45123. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45124. /**
  45125. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45126. */
  45127. get: function () {
  45128. return this._PBRMATERIAL_ALPHABLEND;
  45129. },
  45130. enumerable: true,
  45131. configurable: true
  45132. });
  45133. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45134. /**
  45135. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45136. * They are also discarded below the alpha cutoff threshold to improve performances.
  45137. */
  45138. get: function () {
  45139. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45140. },
  45141. enumerable: true,
  45142. configurable: true
  45143. });
  45144. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45145. /**
  45146. * Gets the image processing configuration used either in this material.
  45147. */
  45148. get: function () {
  45149. return this._imageProcessingConfiguration;
  45150. },
  45151. /**
  45152. * Sets the Default image processing configuration used either in the this material.
  45153. *
  45154. * If sets to null, the scene one is in use.
  45155. */
  45156. set: function (value) {
  45157. this._attachImageProcessingConfiguration(value);
  45158. // Ensure the effect will be rebuilt.
  45159. this._markAllSubMeshesAsTexturesDirty();
  45160. },
  45161. enumerable: true,
  45162. configurable: true
  45163. });
  45164. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45165. /**
  45166. * Gets wether the color curves effect is enabled.
  45167. */
  45168. get: function () {
  45169. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45170. },
  45171. /**
  45172. * Sets wether the color curves effect is enabled.
  45173. */
  45174. set: function (value) {
  45175. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45176. },
  45177. enumerable: true,
  45178. configurable: true
  45179. });
  45180. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45181. /**
  45182. * Gets wether the color grading effect is enabled.
  45183. */
  45184. get: function () {
  45185. return this.imageProcessingConfiguration.colorGradingEnabled;
  45186. },
  45187. /**
  45188. * Gets wether the color grading effect is enabled.
  45189. */
  45190. set: function (value) {
  45191. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45192. },
  45193. enumerable: true,
  45194. configurable: true
  45195. });
  45196. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45197. /**
  45198. * Gets wether tonemapping is enabled or not.
  45199. */
  45200. get: function () {
  45201. return this._imageProcessingConfiguration.toneMappingEnabled;
  45202. },
  45203. /**
  45204. * Sets wether tonemapping is enabled or not
  45205. */
  45206. set: function (value) {
  45207. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45208. },
  45209. enumerable: true,
  45210. configurable: true
  45211. });
  45212. ;
  45213. ;
  45214. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45215. /**
  45216. * The camera exposure used on this material.
  45217. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45218. * This corresponds to a photographic exposure.
  45219. */
  45220. get: function () {
  45221. return this._imageProcessingConfiguration.exposure;
  45222. },
  45223. /**
  45224. * The camera exposure used on this material.
  45225. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45226. * This corresponds to a photographic exposure.
  45227. */
  45228. set: function (value) {
  45229. this._imageProcessingConfiguration.exposure = value;
  45230. },
  45231. enumerable: true,
  45232. configurable: true
  45233. });
  45234. ;
  45235. ;
  45236. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45237. /**
  45238. * Gets The camera contrast used on this material.
  45239. */
  45240. get: function () {
  45241. return this._imageProcessingConfiguration.contrast;
  45242. },
  45243. /**
  45244. * Sets The camera contrast used on this material.
  45245. */
  45246. set: function (value) {
  45247. this._imageProcessingConfiguration.contrast = value;
  45248. },
  45249. enumerable: true,
  45250. configurable: true
  45251. });
  45252. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45253. /**
  45254. * Gets the Color Grading 2D Lookup Texture.
  45255. */
  45256. get: function () {
  45257. return this._imageProcessingConfiguration.colorGradingTexture;
  45258. },
  45259. /**
  45260. * Sets the Color Grading 2D Lookup Texture.
  45261. */
  45262. set: function (value) {
  45263. this._imageProcessingConfiguration.colorGradingTexture = value;
  45264. },
  45265. enumerable: true,
  45266. configurable: true
  45267. });
  45268. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45269. /**
  45270. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45271. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45272. * 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;
  45273. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45274. */
  45275. get: function () {
  45276. return this._imageProcessingConfiguration.colorCurves;
  45277. },
  45278. /**
  45279. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45280. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45281. * 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;
  45282. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45283. */
  45284. set: function (value) {
  45285. this._imageProcessingConfiguration.colorCurves = value;
  45286. },
  45287. enumerable: true,
  45288. configurable: true
  45289. });
  45290. /**
  45291. * Returns the name of this material class.
  45292. */
  45293. PBRMaterial.prototype.getClassName = function () {
  45294. return "PBRMaterial";
  45295. };
  45296. /**
  45297. * Returns an array of the actively used textures.
  45298. * @returns - Array of BaseTextures
  45299. */
  45300. PBRMaterial.prototype.getActiveTextures = function () {
  45301. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45302. if (this._albedoTexture) {
  45303. activeTextures.push(this._albedoTexture);
  45304. }
  45305. if (this._ambientTexture) {
  45306. activeTextures.push(this._ambientTexture);
  45307. }
  45308. if (this._opacityTexture) {
  45309. activeTextures.push(this._opacityTexture);
  45310. }
  45311. if (this._reflectionTexture) {
  45312. activeTextures.push(this._reflectionTexture);
  45313. }
  45314. if (this._emissiveTexture) {
  45315. activeTextures.push(this._emissiveTexture);
  45316. }
  45317. if (this._reflectivityTexture) {
  45318. activeTextures.push(this._reflectivityTexture);
  45319. }
  45320. if (this._metallicTexture) {
  45321. activeTextures.push(this._metallicTexture);
  45322. }
  45323. if (this._microSurfaceTexture) {
  45324. activeTextures.push(this._microSurfaceTexture);
  45325. }
  45326. if (this._bumpTexture) {
  45327. activeTextures.push(this._bumpTexture);
  45328. }
  45329. if (this._lightmapTexture) {
  45330. activeTextures.push(this._lightmapTexture);
  45331. }
  45332. if (this._refractionTexture) {
  45333. activeTextures.push(this._refractionTexture);
  45334. }
  45335. return activeTextures;
  45336. };
  45337. /**
  45338. * Checks to see if a texture is used in the material.
  45339. * @param texture - Base texture to use.
  45340. * @returns - Boolean specifying if a texture is used in the material.
  45341. */
  45342. PBRMaterial.prototype.hasTexture = function (texture) {
  45343. if (_super.prototype.hasTexture.call(this, texture)) {
  45344. return true;
  45345. }
  45346. if (this._albedoTexture === texture) {
  45347. return true;
  45348. }
  45349. if (this._ambientTexture === texture) {
  45350. return true;
  45351. }
  45352. if (this._opacityTexture === texture) {
  45353. return true;
  45354. }
  45355. if (this._reflectionTexture === texture) {
  45356. return true;
  45357. }
  45358. if (this._reflectivityTexture === texture) {
  45359. return true;
  45360. }
  45361. if (this._metallicTexture === texture) {
  45362. return true;
  45363. }
  45364. if (this._microSurfaceTexture === texture) {
  45365. return true;
  45366. }
  45367. if (this._bumpTexture === texture) {
  45368. return true;
  45369. }
  45370. if (this._lightmapTexture === texture) {
  45371. return true;
  45372. }
  45373. if (this._refractionTexture === texture) {
  45374. return true;
  45375. }
  45376. return false;
  45377. };
  45378. /**
  45379. * Makes a duplicate of the current material.
  45380. * @param name - name to use for the new material.
  45381. */
  45382. PBRMaterial.prototype.clone = function (name) {
  45383. var _this = this;
  45384. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45385. clone.id = name;
  45386. clone.name = name;
  45387. return clone;
  45388. };
  45389. /**
  45390. * Serializes this PBR Material.
  45391. * @returns - An object with the serialized material.
  45392. */
  45393. PBRMaterial.prototype.serialize = function () {
  45394. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45395. serializationObject.customType = "BABYLON.PBRMaterial";
  45396. return serializationObject;
  45397. };
  45398. // Statics
  45399. /**
  45400. * Parses a PBR Material from a serialized object.
  45401. * @param source - Serialized object.
  45402. * @param scene - BJS scene instance.
  45403. * @param rootUrl - url for the scene object
  45404. * @returns - PBRMaterial
  45405. */
  45406. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45407. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45408. };
  45409. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45410. /**
  45411. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45412. */
  45413. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45414. /**
  45415. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45416. */
  45417. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45418. /**
  45419. * 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.
  45420. * They are also discarded below the alpha cutoff threshold to improve performances.
  45421. */
  45422. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45423. __decorate([
  45424. BABYLON.serialize(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRMaterial.prototype, "directIntensity", void 0);
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45431. __decorate([
  45432. BABYLON.serialize(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45434. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45435. __decorate([
  45436. BABYLON.serialize(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45438. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45439. __decorate([
  45440. BABYLON.serialize(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45442. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45443. __decorate([
  45444. BABYLON.serializeAsTexture(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45447. __decorate([
  45448. BABYLON.serializeAsTexture(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45451. __decorate([
  45452. BABYLON.serialize(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45455. __decorate([
  45456. BABYLON.serializeAsTexture(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45458. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45459. __decorate([
  45460. BABYLON.serializeAsTexture(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsTexture(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45467. __decorate([
  45468. BABYLON.serializeAsTexture(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45471. __decorate([
  45472. BABYLON.serializeAsTexture(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45475. __decorate([
  45476. BABYLON.serialize(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "metallic", void 0);
  45479. __decorate([
  45480. BABYLON.serialize(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "roughness", void 0);
  45483. __decorate([
  45484. BABYLON.serializeAsTexture(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45487. __decorate([
  45488. BABYLON.serializeAsTexture(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45491. __decorate([
  45492. BABYLON.serializeAsTexture(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45494. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45495. __decorate([
  45496. BABYLON.serializeAsTexture(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45498. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45499. __decorate([
  45500. BABYLON.serializeAsColor3("ambient"),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "ambientColor", void 0);
  45503. __decorate([
  45504. BABYLON.serializeAsColor3("albedo"),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45506. ], PBRMaterial.prototype, "albedoColor", void 0);
  45507. __decorate([
  45508. BABYLON.serializeAsColor3("reflectivity"),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45511. __decorate([
  45512. BABYLON.serializeAsColor3("reflection"),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45514. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45515. __decorate([
  45516. BABYLON.serializeAsColor3("emissive"),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45519. __decorate([
  45520. BABYLON.serialize(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "microSurface", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45527. __decorate([
  45528. BABYLON.serialize(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45542. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45546. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45550. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45578. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45586. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "useParallax", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45610. ], PBRMaterial.prototype, "disableLighting", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45618. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45631. __decorate([
  45632. BABYLON.serialize(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45635. __decorate([
  45636. BABYLON.serialize(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45638. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45639. __decorate([
  45640. BABYLON.serializeAsTexture(),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45642. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45643. __decorate([
  45644. BABYLON.serialize(),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45646. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45647. __decorate([
  45648. BABYLON.serialize(),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45650. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45651. __decorate([
  45652. BABYLON.serialize(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45654. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45655. __decorate([
  45656. BABYLON.serialize(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45658. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45659. __decorate([
  45660. BABYLON.serialize(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45662. ], PBRMaterial.prototype, "unlit", void 0);
  45663. return PBRMaterial;
  45664. }(BABYLON.PBRBaseMaterial));
  45665. BABYLON.PBRMaterial = PBRMaterial;
  45666. })(BABYLON || (BABYLON = {}));
  45667. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45668. var BABYLON;
  45669. (function (BABYLON) {
  45670. /**
  45671. * The PBR material of BJS following the metal roughness convention.
  45672. *
  45673. * This fits to the PBR convention in the GLTF definition:
  45674. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45675. */
  45676. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45677. __extends(PBRMetallicRoughnessMaterial, _super);
  45678. /**
  45679. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45680. *
  45681. * @param name The material name
  45682. * @param scene The scene the material will be use in.
  45683. */
  45684. function PBRMetallicRoughnessMaterial(name, scene) {
  45685. var _this = _super.call(this, name, scene) || this;
  45686. _this._useRoughnessFromMetallicTextureAlpha = false;
  45687. _this._useRoughnessFromMetallicTextureGreen = true;
  45688. _this._useMetallnessFromMetallicTextureBlue = true;
  45689. _this.metallic = 1.0;
  45690. _this.roughness = 1.0;
  45691. return _this;
  45692. }
  45693. /**
  45694. * Return the currrent class name of the material.
  45695. */
  45696. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45697. return "PBRMetallicRoughnessMaterial";
  45698. };
  45699. /**
  45700. * Return the active textures of the material.
  45701. */
  45702. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45703. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45704. if (this.baseTexture) {
  45705. activeTextures.push(this.baseTexture);
  45706. }
  45707. if (this.metallicRoughnessTexture) {
  45708. activeTextures.push(this.metallicRoughnessTexture);
  45709. }
  45710. return activeTextures;
  45711. };
  45712. /**
  45713. * Checks to see if a texture is used in the material.
  45714. * @param texture - Base texture to use.
  45715. * @returns - Boolean specifying if a texture is used in the material.
  45716. */
  45717. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45718. if (_super.prototype.hasTexture.call(this, texture)) {
  45719. return true;
  45720. }
  45721. if (this.baseTexture === texture) {
  45722. return true;
  45723. }
  45724. if (this.metallicRoughnessTexture === texture) {
  45725. return true;
  45726. }
  45727. return false;
  45728. };
  45729. /**
  45730. * Makes a duplicate of the current material.
  45731. * @param name - name to use for the new material.
  45732. */
  45733. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45734. var _this = this;
  45735. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45736. clone.id = name;
  45737. clone.name = name;
  45738. return clone;
  45739. };
  45740. /**
  45741. * Serialize the material to a parsable JSON object.
  45742. */
  45743. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45744. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45745. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45746. return serializationObject;
  45747. };
  45748. /**
  45749. * Parses a JSON object correponding to the serialize function.
  45750. */
  45751. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45752. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45753. };
  45754. __decorate([
  45755. BABYLON.serializeAsColor3(),
  45756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45757. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45758. __decorate([
  45759. BABYLON.serializeAsTexture(),
  45760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45761. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45762. __decorate([
  45763. BABYLON.serialize(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45765. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45766. __decorate([
  45767. BABYLON.serialize(),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45769. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45770. __decorate([
  45771. BABYLON.serializeAsTexture(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45773. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45774. return PBRMetallicRoughnessMaterial;
  45775. }(BABYLON.PBRBaseSimpleMaterial));
  45776. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45777. })(BABYLON || (BABYLON = {}));
  45778. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45779. var BABYLON;
  45780. (function (BABYLON) {
  45781. /**
  45782. * The PBR material of BJS following the specular glossiness convention.
  45783. *
  45784. * This fits to the PBR convention in the GLTF definition:
  45785. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45786. */
  45787. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45788. __extends(PBRSpecularGlossinessMaterial, _super);
  45789. /**
  45790. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45791. *
  45792. * @param name The material name
  45793. * @param scene The scene the material will be use in.
  45794. */
  45795. function PBRSpecularGlossinessMaterial(name, scene) {
  45796. var _this = _super.call(this, name, scene) || this;
  45797. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45798. return _this;
  45799. }
  45800. /**
  45801. * Return the currrent class name of the material.
  45802. */
  45803. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45804. return "PBRSpecularGlossinessMaterial";
  45805. };
  45806. /**
  45807. * Return the active textures of the material.
  45808. */
  45809. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45810. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45811. if (this.diffuseTexture) {
  45812. activeTextures.push(this.diffuseTexture);
  45813. }
  45814. if (this.specularGlossinessTexture) {
  45815. activeTextures.push(this.specularGlossinessTexture);
  45816. }
  45817. return activeTextures;
  45818. };
  45819. /**
  45820. * Checks to see if a texture is used in the material.
  45821. * @param texture - Base texture to use.
  45822. * @returns - Boolean specifying if a texture is used in the material.
  45823. */
  45824. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45825. if (_super.prototype.hasTexture.call(this, texture)) {
  45826. return true;
  45827. }
  45828. if (this.diffuseTexture === texture) {
  45829. return true;
  45830. }
  45831. if (this.specularGlossinessTexture === texture) {
  45832. return true;
  45833. }
  45834. return false;
  45835. };
  45836. /**
  45837. * Makes a duplicate of the current material.
  45838. * @param name - name to use for the new material.
  45839. */
  45840. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45841. var _this = this;
  45842. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45843. clone.id = name;
  45844. clone.name = name;
  45845. return clone;
  45846. };
  45847. /**
  45848. * Serialize the material to a parsable JSON object.
  45849. */
  45850. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45851. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45852. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45853. return serializationObject;
  45854. };
  45855. /**
  45856. * Parses a JSON object correponding to the serialize function.
  45857. */
  45858. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45859. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45860. };
  45861. __decorate([
  45862. BABYLON.serializeAsColor3("diffuse"),
  45863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45864. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45865. __decorate([
  45866. BABYLON.serializeAsTexture(),
  45867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45868. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45869. __decorate([
  45870. BABYLON.serializeAsColor3("specular"),
  45871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45872. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45873. __decorate([
  45874. BABYLON.serialize(),
  45875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45876. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45877. __decorate([
  45878. BABYLON.serializeAsTexture(),
  45879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45880. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45881. return PBRSpecularGlossinessMaterial;
  45882. }(BABYLON.PBRBaseSimpleMaterial));
  45883. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45884. })(BABYLON || (BABYLON = {}));
  45885. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45886. var BABYLON;
  45887. (function (BABYLON) {
  45888. BABYLON.CameraInputTypes = {};
  45889. var CameraInputsManager = /** @class */ (function () {
  45890. function CameraInputsManager(camera) {
  45891. this.attached = {};
  45892. this.camera = camera;
  45893. this.checkInputs = function () { };
  45894. }
  45895. /**
  45896. * Add an input method to a camera.
  45897. * builtin inputs example: camera.inputs.addGamepad();
  45898. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45899. * @param input camera input method
  45900. */
  45901. CameraInputsManager.prototype.add = function (input) {
  45902. var type = input.getSimpleName();
  45903. if (this.attached[type]) {
  45904. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45905. return;
  45906. }
  45907. this.attached[type] = input;
  45908. input.camera = this.camera;
  45909. //for checkInputs, we are dynamically creating a function
  45910. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45911. if (input.checkInputs) {
  45912. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45913. }
  45914. if (this.attachedElement) {
  45915. input.attachControl(this.attachedElement);
  45916. }
  45917. };
  45918. /**
  45919. * Remove a specific input method from a camera
  45920. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45921. * @param inputToRemove camera input method
  45922. */
  45923. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45924. for (var cam in this.attached) {
  45925. var input = this.attached[cam];
  45926. if (input === inputToRemove) {
  45927. input.detachControl(this.attachedElement);
  45928. input.camera = null;
  45929. delete this.attached[cam];
  45930. this.rebuildInputCheck();
  45931. }
  45932. }
  45933. };
  45934. CameraInputsManager.prototype.removeByType = function (inputType) {
  45935. for (var cam in this.attached) {
  45936. var input = this.attached[cam];
  45937. if (input.getClassName() === inputType) {
  45938. input.detachControl(this.attachedElement);
  45939. input.camera = null;
  45940. delete this.attached[cam];
  45941. this.rebuildInputCheck();
  45942. }
  45943. }
  45944. };
  45945. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45946. var current = this.checkInputs;
  45947. return function () {
  45948. current();
  45949. fn();
  45950. };
  45951. };
  45952. CameraInputsManager.prototype.attachInput = function (input) {
  45953. if (this.attachedElement) {
  45954. input.attachControl(this.attachedElement, this.noPreventDefault);
  45955. }
  45956. };
  45957. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45958. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45959. if (this.attachedElement) {
  45960. return;
  45961. }
  45962. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45963. this.attachedElement = element;
  45964. this.noPreventDefault = noPreventDefault;
  45965. for (var cam in this.attached) {
  45966. this.attached[cam].attachControl(element, noPreventDefault);
  45967. }
  45968. };
  45969. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45970. if (disconnect === void 0) { disconnect = false; }
  45971. if (this.attachedElement !== element) {
  45972. return;
  45973. }
  45974. for (var cam in this.attached) {
  45975. this.attached[cam].detachControl(element);
  45976. if (disconnect) {
  45977. this.attached[cam].camera = null;
  45978. }
  45979. }
  45980. this.attachedElement = null;
  45981. };
  45982. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45983. this.checkInputs = function () { };
  45984. for (var cam in this.attached) {
  45985. var input = this.attached[cam];
  45986. if (input.checkInputs) {
  45987. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45988. }
  45989. }
  45990. };
  45991. /**
  45992. * Remove all attached input methods from a camera
  45993. */
  45994. CameraInputsManager.prototype.clear = function () {
  45995. if (this.attachedElement) {
  45996. this.detachElement(this.attachedElement, true);
  45997. }
  45998. this.attached = {};
  45999. this.attachedElement = null;
  46000. this.checkInputs = function () { };
  46001. };
  46002. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46003. var inputs = {};
  46004. for (var cam in this.attached) {
  46005. var input = this.attached[cam];
  46006. var res = BABYLON.SerializationHelper.Serialize(input);
  46007. inputs[input.getClassName()] = res;
  46008. }
  46009. serializedCamera.inputsmgr = inputs;
  46010. };
  46011. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46012. var parsedInputs = parsedCamera.inputsmgr;
  46013. if (parsedInputs) {
  46014. this.clear();
  46015. for (var n in parsedInputs) {
  46016. var construct = BABYLON.CameraInputTypes[n];
  46017. if (construct) {
  46018. var parsedinput = parsedInputs[n];
  46019. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46020. this.add(input);
  46021. }
  46022. }
  46023. }
  46024. else {
  46025. //2016-03-08 this part is for managing backward compatibility
  46026. for (var n in this.attached) {
  46027. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46028. if (construct) {
  46029. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46030. this.remove(this.attached[n]);
  46031. this.add(input);
  46032. }
  46033. }
  46034. }
  46035. };
  46036. return CameraInputsManager;
  46037. }());
  46038. BABYLON.CameraInputsManager = CameraInputsManager;
  46039. })(BABYLON || (BABYLON = {}));
  46040. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46041. var BABYLON;
  46042. (function (BABYLON) {
  46043. var TargetCamera = /** @class */ (function (_super) {
  46044. __extends(TargetCamera, _super);
  46045. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46046. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46047. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46048. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46049. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46050. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46051. _this.speed = 2.0;
  46052. _this.noRotationConstraint = false;
  46053. _this.lockedTarget = null;
  46054. _this._currentTarget = BABYLON.Vector3.Zero();
  46055. _this._viewMatrix = BABYLON.Matrix.Zero();
  46056. _this._camMatrix = BABYLON.Matrix.Zero();
  46057. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46058. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46059. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46060. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46061. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46062. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46063. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46064. return _this;
  46065. }
  46066. TargetCamera.prototype.getFrontPosition = function (distance) {
  46067. this.getWorldMatrix();
  46068. var direction = this.getTarget().subtract(this.position);
  46069. direction.normalize();
  46070. direction.scaleInPlace(distance);
  46071. return this.globalPosition.add(direction);
  46072. };
  46073. TargetCamera.prototype._getLockedTargetPosition = function () {
  46074. if (!this.lockedTarget) {
  46075. return null;
  46076. }
  46077. if (this.lockedTarget.absolutePosition) {
  46078. this.lockedTarget.computeWorldMatrix();
  46079. }
  46080. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46081. };
  46082. TargetCamera.prototype.storeState = function () {
  46083. this._storedPosition = this.position.clone();
  46084. this._storedRotation = this.rotation.clone();
  46085. if (this.rotationQuaternion) {
  46086. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46087. }
  46088. return _super.prototype.storeState.call(this);
  46089. };
  46090. /**
  46091. * Restored camera state. You must call storeState() first
  46092. */
  46093. TargetCamera.prototype._restoreStateValues = function () {
  46094. if (!_super.prototype._restoreStateValues.call(this)) {
  46095. return false;
  46096. }
  46097. this.position = this._storedPosition.clone();
  46098. this.rotation = this._storedRotation.clone();
  46099. if (this.rotationQuaternion) {
  46100. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46101. }
  46102. this.cameraDirection.copyFromFloats(0, 0, 0);
  46103. this.cameraRotation.copyFromFloats(0, 0);
  46104. return true;
  46105. };
  46106. // Cache
  46107. TargetCamera.prototype._initCache = function () {
  46108. _super.prototype._initCache.call(this);
  46109. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46110. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46111. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46112. };
  46113. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46114. if (!ignoreParentClass) {
  46115. _super.prototype._updateCache.call(this);
  46116. }
  46117. var lockedTargetPosition = this._getLockedTargetPosition();
  46118. if (!lockedTargetPosition) {
  46119. this._cache.lockedTarget = null;
  46120. }
  46121. else {
  46122. if (!this._cache.lockedTarget) {
  46123. this._cache.lockedTarget = lockedTargetPosition.clone();
  46124. }
  46125. else {
  46126. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46127. }
  46128. }
  46129. this._cache.rotation.copyFrom(this.rotation);
  46130. if (this.rotationQuaternion)
  46131. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46132. };
  46133. // Synchronized
  46134. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46135. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46136. return false;
  46137. }
  46138. var lockedTargetPosition = this._getLockedTargetPosition();
  46139. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46140. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46141. };
  46142. // Methods
  46143. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46144. var engine = this.getEngine();
  46145. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46146. };
  46147. // Target
  46148. TargetCamera.prototype.setTarget = function (target) {
  46149. this.upVector.normalize();
  46150. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46151. this._camMatrix.invert();
  46152. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46153. var vDir = target.subtract(this.position);
  46154. if (vDir.x >= 0.0) {
  46155. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46156. }
  46157. else {
  46158. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46159. }
  46160. this.rotation.z = 0;
  46161. if (isNaN(this.rotation.x)) {
  46162. this.rotation.x = 0;
  46163. }
  46164. if (isNaN(this.rotation.y)) {
  46165. this.rotation.y = 0;
  46166. }
  46167. if (isNaN(this.rotation.z)) {
  46168. this.rotation.z = 0;
  46169. }
  46170. if (this.rotationQuaternion) {
  46171. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46172. }
  46173. };
  46174. /**
  46175. * Return the current target position of the camera. This value is expressed in local space.
  46176. */
  46177. TargetCamera.prototype.getTarget = function () {
  46178. return this._currentTarget;
  46179. };
  46180. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46181. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46182. };
  46183. TargetCamera.prototype._updatePosition = function () {
  46184. if (this.parent) {
  46185. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46186. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46187. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46188. return;
  46189. }
  46190. this.position.addInPlace(this.cameraDirection);
  46191. };
  46192. TargetCamera.prototype._checkInputs = function () {
  46193. var needToMove = this._decideIfNeedsToMove();
  46194. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46195. // Move
  46196. if (needToMove) {
  46197. this._updatePosition();
  46198. }
  46199. // Rotate
  46200. if (needToRotate) {
  46201. this.rotation.x += this.cameraRotation.x;
  46202. this.rotation.y += this.cameraRotation.y;
  46203. //rotate, if quaternion is set and rotation was used
  46204. if (this.rotationQuaternion) {
  46205. var len = this.rotation.lengthSquared();
  46206. if (len) {
  46207. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46208. }
  46209. }
  46210. if (!this.noRotationConstraint) {
  46211. var limit = (Math.PI / 2) * 0.95;
  46212. if (this.rotation.x > limit)
  46213. this.rotation.x = limit;
  46214. if (this.rotation.x < -limit)
  46215. this.rotation.x = -limit;
  46216. }
  46217. }
  46218. // Inertia
  46219. if (needToMove) {
  46220. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46221. this.cameraDirection.x = 0;
  46222. }
  46223. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46224. this.cameraDirection.y = 0;
  46225. }
  46226. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46227. this.cameraDirection.z = 0;
  46228. }
  46229. this.cameraDirection.scaleInPlace(this.inertia);
  46230. }
  46231. if (needToRotate) {
  46232. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46233. this.cameraRotation.x = 0;
  46234. }
  46235. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46236. this.cameraRotation.y = 0;
  46237. }
  46238. this.cameraRotation.scaleInPlace(this.inertia);
  46239. }
  46240. _super.prototype._checkInputs.call(this);
  46241. };
  46242. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46243. if (this.rotationQuaternion) {
  46244. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46245. }
  46246. else {
  46247. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46248. }
  46249. //update the up vector!
  46250. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46251. };
  46252. TargetCamera.prototype._getViewMatrix = function () {
  46253. if (this.lockedTarget) {
  46254. this.setTarget(this._getLockedTargetPosition());
  46255. }
  46256. // Compute
  46257. this._updateCameraRotationMatrix();
  46258. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46259. // Computing target and final matrix
  46260. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46261. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46262. return this._viewMatrix;
  46263. };
  46264. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46265. if (this.parent) {
  46266. var parentWorldMatrix = this.parent.getWorldMatrix();
  46267. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46268. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46269. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46270. this._markSyncedWithParent();
  46271. }
  46272. else {
  46273. this._globalPosition.copyFrom(this.position);
  46274. this._globalCurrentTarget.copyFrom(target);
  46275. this._globalCurrentUpVector.copyFrom(up);
  46276. }
  46277. if (this.getScene().useRightHandedSystem) {
  46278. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46279. }
  46280. else {
  46281. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46282. }
  46283. };
  46284. /**
  46285. * @override
  46286. * Override Camera.createRigCamera
  46287. */
  46288. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46289. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46290. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46291. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46292. if (!this.rotationQuaternion) {
  46293. this.rotationQuaternion = new BABYLON.Quaternion();
  46294. }
  46295. rigCamera._cameraRigParams = {};
  46296. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46297. }
  46298. return rigCamera;
  46299. }
  46300. return null;
  46301. };
  46302. /**
  46303. * @override
  46304. * Override Camera._updateRigCameras
  46305. */
  46306. TargetCamera.prototype._updateRigCameras = function () {
  46307. var camLeft = this._rigCameras[0];
  46308. var camRight = this._rigCameras[1];
  46309. switch (this.cameraRigMode) {
  46310. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46312. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46314. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46315. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46316. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46317. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46318. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46319. camLeft.setTarget(this.getTarget());
  46320. camRight.setTarget(this.getTarget());
  46321. break;
  46322. case BABYLON.Camera.RIG_MODE_VR:
  46323. if (camLeft.rotationQuaternion) {
  46324. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46325. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46326. }
  46327. else {
  46328. camLeft.rotation.copyFrom(this.rotation);
  46329. camRight.rotation.copyFrom(this.rotation);
  46330. }
  46331. camLeft.position.copyFrom(this.position);
  46332. camRight.position.copyFrom(this.position);
  46333. break;
  46334. }
  46335. _super.prototype._updateRigCameras.call(this);
  46336. };
  46337. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46338. if (!this._rigCamTransformMatrix) {
  46339. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46340. }
  46341. var target = this.getTarget();
  46342. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46343. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46344. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46345. };
  46346. TargetCamera.prototype.getClassName = function () {
  46347. return "TargetCamera";
  46348. };
  46349. __decorate([
  46350. BABYLON.serializeAsVector3()
  46351. ], TargetCamera.prototype, "rotation", void 0);
  46352. __decorate([
  46353. BABYLON.serialize()
  46354. ], TargetCamera.prototype, "speed", void 0);
  46355. __decorate([
  46356. BABYLON.serializeAsMeshReference("lockedTargetId")
  46357. ], TargetCamera.prototype, "lockedTarget", void 0);
  46358. return TargetCamera;
  46359. }(BABYLON.Camera));
  46360. BABYLON.TargetCamera = TargetCamera;
  46361. })(BABYLON || (BABYLON = {}));
  46362. //# sourceMappingURL=babylon.targetCamera.js.map
  46363. var BABYLON;
  46364. (function (BABYLON) {
  46365. var FreeCameraMouseInput = /** @class */ (function () {
  46366. function FreeCameraMouseInput(touchEnabled) {
  46367. if (touchEnabled === void 0) { touchEnabled = true; }
  46368. this.touchEnabled = touchEnabled;
  46369. this.buttons = [0, 1, 2];
  46370. this.angularSensibility = 2000.0;
  46371. this.previousPosition = null;
  46372. }
  46373. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46374. var _this = this;
  46375. var engine = this.camera.getEngine();
  46376. if (!this._pointerInput) {
  46377. this._pointerInput = function (p, s) {
  46378. var evt = p.event;
  46379. if (engine.isInVRExclusivePointerMode) {
  46380. return;
  46381. }
  46382. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46383. return;
  46384. }
  46385. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46386. return;
  46387. }
  46388. var srcElement = (evt.srcElement || evt.target);
  46389. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46390. try {
  46391. srcElement.setPointerCapture(evt.pointerId);
  46392. }
  46393. catch (e) {
  46394. //Nothing to do with the error. Execution will continue.
  46395. }
  46396. _this.previousPosition = {
  46397. x: evt.clientX,
  46398. y: evt.clientY
  46399. };
  46400. if (!noPreventDefault) {
  46401. evt.preventDefault();
  46402. element.focus();
  46403. }
  46404. }
  46405. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46406. try {
  46407. srcElement.releasePointerCapture(evt.pointerId);
  46408. }
  46409. catch (e) {
  46410. //Nothing to do with the error.
  46411. }
  46412. _this.previousPosition = null;
  46413. if (!noPreventDefault) {
  46414. evt.preventDefault();
  46415. }
  46416. }
  46417. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46418. if (!_this.previousPosition || engine.isPointerLock) {
  46419. return;
  46420. }
  46421. var offsetX = evt.clientX - _this.previousPosition.x;
  46422. if (_this.camera.getScene().useRightHandedSystem)
  46423. offsetX *= -1;
  46424. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46425. offsetX *= -1;
  46426. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46427. var offsetY = evt.clientY - _this.previousPosition.y;
  46428. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46429. _this.previousPosition = {
  46430. x: evt.clientX,
  46431. y: evt.clientY
  46432. };
  46433. if (!noPreventDefault) {
  46434. evt.preventDefault();
  46435. }
  46436. }
  46437. };
  46438. }
  46439. this._onMouseMove = function (evt) {
  46440. if (!engine.isPointerLock) {
  46441. return;
  46442. }
  46443. if (engine.isInVRExclusivePointerMode) {
  46444. return;
  46445. }
  46446. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46447. if (_this.camera.getScene().useRightHandedSystem)
  46448. offsetX *= -1;
  46449. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46450. offsetX *= -1;
  46451. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46452. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46453. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46454. _this.previousPosition = null;
  46455. if (!noPreventDefault) {
  46456. evt.preventDefault();
  46457. }
  46458. };
  46459. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46460. element.addEventListener("mousemove", this._onMouseMove, false);
  46461. };
  46462. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46463. if (this._observer && element) {
  46464. this.camera.getScene().onPointerObservable.remove(this._observer);
  46465. if (this._onMouseMove) {
  46466. element.removeEventListener("mousemove", this._onMouseMove);
  46467. }
  46468. this._observer = null;
  46469. this._onMouseMove = null;
  46470. this.previousPosition = null;
  46471. }
  46472. };
  46473. FreeCameraMouseInput.prototype.getClassName = function () {
  46474. return "FreeCameraMouseInput";
  46475. };
  46476. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46477. return "mouse";
  46478. };
  46479. __decorate([
  46480. BABYLON.serialize()
  46481. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46482. __decorate([
  46483. BABYLON.serialize()
  46484. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46485. return FreeCameraMouseInput;
  46486. }());
  46487. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46488. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46489. })(BABYLON || (BABYLON = {}));
  46490. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46491. var BABYLON;
  46492. (function (BABYLON) {
  46493. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46494. function FreeCameraKeyboardMoveInput() {
  46495. this._keys = new Array();
  46496. this.keysUp = [38];
  46497. this.keysDown = [40];
  46498. this.keysLeft = [37];
  46499. this.keysRight = [39];
  46500. }
  46501. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46502. var _this = this;
  46503. if (this._onCanvasBlurObserver) {
  46504. return;
  46505. }
  46506. this._scene = this.camera.getScene();
  46507. this._engine = this._scene.getEngine();
  46508. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46509. _this._keys = [];
  46510. });
  46511. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46512. var evt = info.event;
  46513. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46514. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46515. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46516. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46517. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46518. var index = _this._keys.indexOf(evt.keyCode);
  46519. if (index === -1) {
  46520. _this._keys.push(evt.keyCode);
  46521. }
  46522. if (!noPreventDefault) {
  46523. evt.preventDefault();
  46524. }
  46525. }
  46526. }
  46527. else {
  46528. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46529. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46530. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46531. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46532. var index = _this._keys.indexOf(evt.keyCode);
  46533. if (index >= 0) {
  46534. _this._keys.splice(index, 1);
  46535. }
  46536. if (!noPreventDefault) {
  46537. evt.preventDefault();
  46538. }
  46539. }
  46540. }
  46541. });
  46542. };
  46543. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46544. if (this._scene) {
  46545. if (this._onKeyboardObserver) {
  46546. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46547. }
  46548. if (this._onCanvasBlurObserver) {
  46549. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46550. }
  46551. this._onKeyboardObserver = null;
  46552. this._onCanvasBlurObserver = null;
  46553. }
  46554. this._keys = [];
  46555. };
  46556. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46557. if (this._onKeyboardObserver) {
  46558. var camera = this.camera;
  46559. // Keyboard
  46560. for (var index = 0; index < this._keys.length; index++) {
  46561. var keyCode = this._keys[index];
  46562. var speed = camera._computeLocalCameraSpeed();
  46563. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46564. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46565. }
  46566. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46567. camera._localDirection.copyFromFloats(0, 0, speed);
  46568. }
  46569. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46570. camera._localDirection.copyFromFloats(speed, 0, 0);
  46571. }
  46572. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46573. camera._localDirection.copyFromFloats(0, 0, -speed);
  46574. }
  46575. if (camera.getScene().useRightHandedSystem) {
  46576. camera._localDirection.z *= -1;
  46577. }
  46578. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46579. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46580. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46581. }
  46582. }
  46583. };
  46584. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46585. return "FreeCameraKeyboardMoveInput";
  46586. };
  46587. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46588. this._keys = [];
  46589. };
  46590. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46591. return "keyboard";
  46592. };
  46593. __decorate([
  46594. BABYLON.serialize()
  46595. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46596. __decorate([
  46597. BABYLON.serialize()
  46598. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46599. __decorate([
  46600. BABYLON.serialize()
  46601. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46602. __decorate([
  46603. BABYLON.serialize()
  46604. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46605. return FreeCameraKeyboardMoveInput;
  46606. }());
  46607. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46608. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46609. })(BABYLON || (BABYLON = {}));
  46610. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46611. var BABYLON;
  46612. (function (BABYLON) {
  46613. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46614. __extends(FreeCameraInputsManager, _super);
  46615. function FreeCameraInputsManager(camera) {
  46616. return _super.call(this, camera) || this;
  46617. }
  46618. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46619. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46620. return this;
  46621. };
  46622. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46623. if (touchEnabled === void 0) { touchEnabled = true; }
  46624. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46625. return this;
  46626. };
  46627. FreeCameraInputsManager.prototype.addGamepad = function () {
  46628. this.add(new BABYLON.FreeCameraGamepadInput());
  46629. return this;
  46630. };
  46631. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46632. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46633. return this;
  46634. };
  46635. FreeCameraInputsManager.prototype.addTouch = function () {
  46636. this.add(new BABYLON.FreeCameraTouchInput());
  46637. return this;
  46638. };
  46639. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46640. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46641. return this;
  46642. };
  46643. return FreeCameraInputsManager;
  46644. }(BABYLON.CameraInputsManager));
  46645. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46646. })(BABYLON || (BABYLON = {}));
  46647. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46648. var BABYLON;
  46649. (function (BABYLON) {
  46650. var FreeCamera = /** @class */ (function (_super) {
  46651. __extends(FreeCamera, _super);
  46652. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46653. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46654. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46655. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46656. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46657. _this.checkCollisions = false;
  46658. _this.applyGravity = false;
  46659. _this._needMoveForGravity = false;
  46660. _this._oldPosition = BABYLON.Vector3.Zero();
  46661. _this._diffPosition = BABYLON.Vector3.Zero();
  46662. _this._newPosition = BABYLON.Vector3.Zero();
  46663. // Collisions
  46664. _this._collisionMask = -1;
  46665. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46666. if (collidedMesh === void 0) { collidedMesh = null; }
  46667. //TODO move this to the collision coordinator!
  46668. if (_this.getScene().workerCollisions)
  46669. newPosition.multiplyInPlace(_this._collider._radius);
  46670. var updatePosition = function (newPos) {
  46671. _this._newPosition.copyFrom(newPos);
  46672. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46673. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46674. _this.position.addInPlace(_this._diffPosition);
  46675. if (_this.onCollide && collidedMesh) {
  46676. _this.onCollide(collidedMesh);
  46677. }
  46678. }
  46679. };
  46680. updatePosition(newPosition);
  46681. };
  46682. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46683. _this.inputs.addKeyboard().addMouse();
  46684. return _this;
  46685. }
  46686. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46687. //-- begin properties for backward compatibility for inputs
  46688. /**
  46689. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46690. * Higher values reduce sensitivity.
  46691. */
  46692. get: function () {
  46693. var mouse = this.inputs.attached["mouse"];
  46694. if (mouse)
  46695. return mouse.angularSensibility;
  46696. return 0;
  46697. },
  46698. /**
  46699. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46700. * Higher values reduce sensitivity.
  46701. */
  46702. set: function (value) {
  46703. var mouse = this.inputs.attached["mouse"];
  46704. if (mouse)
  46705. mouse.angularSensibility = value;
  46706. },
  46707. enumerable: true,
  46708. configurable: true
  46709. });
  46710. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46711. get: function () {
  46712. var keyboard = this.inputs.attached["keyboard"];
  46713. if (keyboard)
  46714. return keyboard.keysUp;
  46715. return [];
  46716. },
  46717. set: function (value) {
  46718. var keyboard = this.inputs.attached["keyboard"];
  46719. if (keyboard)
  46720. keyboard.keysUp = value;
  46721. },
  46722. enumerable: true,
  46723. configurable: true
  46724. });
  46725. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46726. get: function () {
  46727. var keyboard = this.inputs.attached["keyboard"];
  46728. if (keyboard)
  46729. return keyboard.keysDown;
  46730. return [];
  46731. },
  46732. set: function (value) {
  46733. var keyboard = this.inputs.attached["keyboard"];
  46734. if (keyboard)
  46735. keyboard.keysDown = value;
  46736. },
  46737. enumerable: true,
  46738. configurable: true
  46739. });
  46740. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46741. get: function () {
  46742. var keyboard = this.inputs.attached["keyboard"];
  46743. if (keyboard)
  46744. return keyboard.keysLeft;
  46745. return [];
  46746. },
  46747. set: function (value) {
  46748. var keyboard = this.inputs.attached["keyboard"];
  46749. if (keyboard)
  46750. keyboard.keysLeft = value;
  46751. },
  46752. enumerable: true,
  46753. configurable: true
  46754. });
  46755. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46756. get: function () {
  46757. var keyboard = this.inputs.attached["keyboard"];
  46758. if (keyboard)
  46759. return keyboard.keysRight;
  46760. return [];
  46761. },
  46762. set: function (value) {
  46763. var keyboard = this.inputs.attached["keyboard"];
  46764. if (keyboard)
  46765. keyboard.keysRight = value;
  46766. },
  46767. enumerable: true,
  46768. configurable: true
  46769. });
  46770. // Controls
  46771. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46772. this.inputs.attachElement(element, noPreventDefault);
  46773. };
  46774. FreeCamera.prototype.detachControl = function (element) {
  46775. this.inputs.detachElement(element);
  46776. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46777. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46778. };
  46779. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46780. get: function () {
  46781. return this._collisionMask;
  46782. },
  46783. set: function (mask) {
  46784. this._collisionMask = !isNaN(mask) ? mask : -1;
  46785. },
  46786. enumerable: true,
  46787. configurable: true
  46788. });
  46789. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46790. var globalPosition;
  46791. if (this.parent) {
  46792. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46793. }
  46794. else {
  46795. globalPosition = this.position;
  46796. }
  46797. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46798. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46799. if (!this._collider) {
  46800. this._collider = new BABYLON.Collider();
  46801. }
  46802. this._collider._radius = this.ellipsoid;
  46803. this._collider.collisionMask = this._collisionMask;
  46804. //no need for clone, as long as gravity is not on.
  46805. var actualDisplacement = displacement;
  46806. //add gravity to the direction to prevent the dual-collision checking
  46807. if (this.applyGravity) {
  46808. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46809. actualDisplacement = displacement.add(this.getScene().gravity);
  46810. }
  46811. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46812. };
  46813. FreeCamera.prototype._checkInputs = function () {
  46814. if (!this._localDirection) {
  46815. this._localDirection = BABYLON.Vector3.Zero();
  46816. this._transformedDirection = BABYLON.Vector3.Zero();
  46817. }
  46818. this.inputs.checkInputs();
  46819. _super.prototype._checkInputs.call(this);
  46820. };
  46821. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46822. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46823. };
  46824. FreeCamera.prototype._updatePosition = function () {
  46825. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46826. this._collideWithWorld(this.cameraDirection);
  46827. }
  46828. else {
  46829. _super.prototype._updatePosition.call(this);
  46830. }
  46831. };
  46832. FreeCamera.prototype.dispose = function () {
  46833. this.inputs.clear();
  46834. _super.prototype.dispose.call(this);
  46835. };
  46836. FreeCamera.prototype.getClassName = function () {
  46837. return "FreeCamera";
  46838. };
  46839. __decorate([
  46840. BABYLON.serializeAsVector3()
  46841. ], FreeCamera.prototype, "ellipsoid", void 0);
  46842. __decorate([
  46843. BABYLON.serializeAsVector3()
  46844. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46845. __decorate([
  46846. BABYLON.serialize()
  46847. ], FreeCamera.prototype, "checkCollisions", void 0);
  46848. __decorate([
  46849. BABYLON.serialize()
  46850. ], FreeCamera.prototype, "applyGravity", void 0);
  46851. return FreeCamera;
  46852. }(BABYLON.TargetCamera));
  46853. BABYLON.FreeCamera = FreeCamera;
  46854. })(BABYLON || (BABYLON = {}));
  46855. //# sourceMappingURL=babylon.freeCamera.js.map
  46856. var BABYLON;
  46857. (function (BABYLON) {
  46858. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46859. function ArcRotateCameraKeyboardMoveInput() {
  46860. this._keys = new Array();
  46861. this.keysUp = [38];
  46862. this.keysDown = [40];
  46863. this.keysLeft = [37];
  46864. this.keysRight = [39];
  46865. this.keysReset = [220];
  46866. this.panningSensibility = 50.0;
  46867. this.zoomingSensibility = 25.0;
  46868. this.useAltToZoom = true;
  46869. }
  46870. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46871. var _this = this;
  46872. if (this._onCanvasBlurObserver) {
  46873. return;
  46874. }
  46875. this._scene = this.camera.getScene();
  46876. this._engine = this._scene.getEngine();
  46877. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46878. _this._keys = [];
  46879. });
  46880. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46881. var evt = info.event;
  46882. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46883. _this._ctrlPressed = evt.ctrlKey;
  46884. _this._altPressed = evt.altKey;
  46885. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46886. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46887. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46888. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46889. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46890. var index = _this._keys.indexOf(evt.keyCode);
  46891. if (index === -1) {
  46892. _this._keys.push(evt.keyCode);
  46893. }
  46894. if (evt.preventDefault) {
  46895. if (!noPreventDefault) {
  46896. evt.preventDefault();
  46897. }
  46898. }
  46899. }
  46900. }
  46901. else {
  46902. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46903. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46904. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46905. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46906. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46907. var index = _this._keys.indexOf(evt.keyCode);
  46908. if (index >= 0) {
  46909. _this._keys.splice(index, 1);
  46910. }
  46911. if (evt.preventDefault) {
  46912. if (!noPreventDefault) {
  46913. evt.preventDefault();
  46914. }
  46915. }
  46916. }
  46917. }
  46918. });
  46919. };
  46920. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46921. if (this._scene) {
  46922. if (this._onKeyboardObserver) {
  46923. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46924. }
  46925. if (this._onCanvasBlurObserver) {
  46926. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46927. }
  46928. this._onKeyboardObserver = null;
  46929. this._onCanvasBlurObserver = null;
  46930. }
  46931. this._keys = [];
  46932. };
  46933. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46934. if (this._onKeyboardObserver) {
  46935. var camera = this.camera;
  46936. for (var index = 0; index < this._keys.length; index++) {
  46937. var keyCode = this._keys[index];
  46938. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46939. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46940. camera.inertialPanningX -= 1 / this.panningSensibility;
  46941. }
  46942. else {
  46943. camera.inertialAlphaOffset -= 0.01;
  46944. }
  46945. }
  46946. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46947. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46948. camera.inertialPanningY += 1 / this.panningSensibility;
  46949. }
  46950. else if (this._altPressed && this.useAltToZoom) {
  46951. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46952. }
  46953. else {
  46954. camera.inertialBetaOffset -= 0.01;
  46955. }
  46956. }
  46957. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46958. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46959. camera.inertialPanningX += 1 / this.panningSensibility;
  46960. }
  46961. else {
  46962. camera.inertialAlphaOffset += 0.01;
  46963. }
  46964. }
  46965. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46966. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46967. camera.inertialPanningY -= 1 / this.panningSensibility;
  46968. }
  46969. else if (this._altPressed && this.useAltToZoom) {
  46970. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46971. }
  46972. else {
  46973. camera.inertialBetaOffset += 0.01;
  46974. }
  46975. }
  46976. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46977. camera.restoreState();
  46978. }
  46979. }
  46980. }
  46981. };
  46982. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46983. return "ArcRotateCameraKeyboardMoveInput";
  46984. };
  46985. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46986. return "keyboard";
  46987. };
  46988. __decorate([
  46989. BABYLON.serialize()
  46990. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46991. __decorate([
  46992. BABYLON.serialize()
  46993. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46994. __decorate([
  46995. BABYLON.serialize()
  46996. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46997. __decorate([
  46998. BABYLON.serialize()
  46999. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47000. __decorate([
  47001. BABYLON.serialize()
  47002. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47003. __decorate([
  47004. BABYLON.serialize()
  47005. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47006. __decorate([
  47007. BABYLON.serialize()
  47008. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47009. __decorate([
  47010. BABYLON.serialize()
  47011. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47012. return ArcRotateCameraKeyboardMoveInput;
  47013. }());
  47014. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47015. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47016. })(BABYLON || (BABYLON = {}));
  47017. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47018. var BABYLON;
  47019. (function (BABYLON) {
  47020. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47021. function ArcRotateCameraMouseWheelInput() {
  47022. this.wheelPrecision = 3.0;
  47023. /**
  47024. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47025. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47026. */
  47027. this.wheelDeltaPercentage = 0;
  47028. }
  47029. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47030. var _this = this;
  47031. this._wheel = function (p, s) {
  47032. //sanity check - this should be a PointerWheel event.
  47033. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47034. return;
  47035. var event = p.event;
  47036. var delta = 0;
  47037. if (event.wheelDelta) {
  47038. if (_this.wheelDeltaPercentage) {
  47039. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47040. if (event.wheelDelta > 0) {
  47041. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47042. }
  47043. else {
  47044. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47045. }
  47046. }
  47047. else {
  47048. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47049. }
  47050. }
  47051. else if (event.detail) {
  47052. delta = -event.detail / _this.wheelPrecision;
  47053. }
  47054. if (delta)
  47055. _this.camera.inertialRadiusOffset += delta;
  47056. if (event.preventDefault) {
  47057. if (!noPreventDefault) {
  47058. event.preventDefault();
  47059. }
  47060. }
  47061. };
  47062. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47063. };
  47064. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47065. if (this._observer && element) {
  47066. this.camera.getScene().onPointerObservable.remove(this._observer);
  47067. this._observer = null;
  47068. this._wheel = null;
  47069. }
  47070. };
  47071. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47072. return "ArcRotateCameraMouseWheelInput";
  47073. };
  47074. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47075. return "mousewheel";
  47076. };
  47077. __decorate([
  47078. BABYLON.serialize()
  47079. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47080. __decorate([
  47081. BABYLON.serialize()
  47082. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47083. return ArcRotateCameraMouseWheelInput;
  47084. }());
  47085. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47086. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47087. })(BABYLON || (BABYLON = {}));
  47088. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47089. var BABYLON;
  47090. (function (BABYLON) {
  47091. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47092. function ArcRotateCameraPointersInput() {
  47093. this.buttons = [0, 1, 2];
  47094. this.angularSensibilityX = 1000.0;
  47095. this.angularSensibilityY = 1000.0;
  47096. this.pinchPrecision = 12.0;
  47097. /**
  47098. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47099. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47100. */
  47101. this.pinchDeltaPercentage = 0;
  47102. this.panningSensibility = 1000.0;
  47103. this.multiTouchPanning = true;
  47104. this.multiTouchPanAndZoom = true;
  47105. this._isPanClick = false;
  47106. this.pinchInwards = true;
  47107. }
  47108. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47109. var _this = this;
  47110. var engine = this.camera.getEngine();
  47111. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47112. var pointA = null;
  47113. var pointB = null;
  47114. var previousPinchSquaredDistance = 0;
  47115. var initialDistance = 0;
  47116. var twoFingerActivityCount = 0;
  47117. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47118. this._pointerInput = function (p, s) {
  47119. var evt = p.event;
  47120. var isTouch = p.event.pointerType === "touch";
  47121. if (engine.isInVRExclusivePointerMode) {
  47122. return;
  47123. }
  47124. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47125. return;
  47126. }
  47127. var srcElement = (evt.srcElement || evt.target);
  47128. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47129. try {
  47130. srcElement.setPointerCapture(evt.pointerId);
  47131. }
  47132. catch (e) {
  47133. //Nothing to do with the error. Execution will continue.
  47134. }
  47135. // Manage panning with pan button click
  47136. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47137. // manage pointers
  47138. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47139. if (pointA === null) {
  47140. pointA = cacheSoloPointer;
  47141. }
  47142. else if (pointB === null) {
  47143. pointB = cacheSoloPointer;
  47144. }
  47145. if (!noPreventDefault) {
  47146. evt.preventDefault();
  47147. element.focus();
  47148. }
  47149. }
  47150. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47151. _this.camera.restoreState();
  47152. }
  47153. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47154. try {
  47155. srcElement.releasePointerCapture(evt.pointerId);
  47156. }
  47157. catch (e) {
  47158. //Nothing to do with the error.
  47159. }
  47160. cacheSoloPointer = null;
  47161. previousPinchSquaredDistance = 0;
  47162. previousMultiTouchPanPosition.isPaning = false;
  47163. previousMultiTouchPanPosition.isPinching = false;
  47164. twoFingerActivityCount = 0;
  47165. initialDistance = 0;
  47166. if (!isTouch) {
  47167. pointB = null; // Mouse and pen are mono pointer
  47168. }
  47169. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47170. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47171. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47172. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47173. if (engine._badOS) {
  47174. pointA = pointB = null;
  47175. }
  47176. else {
  47177. //only remove the impacted pointer in case of multitouch allowing on most
  47178. //platforms switching from rotate to zoom and pan seamlessly.
  47179. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47180. pointA = pointB;
  47181. pointB = null;
  47182. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47183. }
  47184. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47185. pointB = null;
  47186. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47187. }
  47188. else {
  47189. pointA = pointB = null;
  47190. }
  47191. }
  47192. if (!noPreventDefault) {
  47193. evt.preventDefault();
  47194. }
  47195. }
  47196. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47197. if (!noPreventDefault) {
  47198. evt.preventDefault();
  47199. }
  47200. // One button down
  47201. if (pointA && pointB === null && cacheSoloPointer) {
  47202. if (_this.panningSensibility !== 0 &&
  47203. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47204. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47205. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47206. }
  47207. else {
  47208. var offsetX = evt.clientX - cacheSoloPointer.x;
  47209. var offsetY = evt.clientY - cacheSoloPointer.y;
  47210. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47211. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47212. }
  47213. cacheSoloPointer.x = evt.clientX;
  47214. cacheSoloPointer.y = evt.clientY;
  47215. }
  47216. // Two buttons down: pinch/pan
  47217. else if (pointA && pointB) {
  47218. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47219. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47220. ed.x = evt.clientX;
  47221. ed.y = evt.clientY;
  47222. var direction = _this.pinchInwards ? 1 : -1;
  47223. var distX = pointA.x - pointB.x;
  47224. var distY = pointA.y - pointB.y;
  47225. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47226. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47227. if (previousPinchSquaredDistance === 0) {
  47228. initialDistance = pinchDistance;
  47229. previousPinchSquaredDistance = pinchSquaredDistance;
  47230. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47231. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47232. return;
  47233. }
  47234. if (_this.multiTouchPanAndZoom) {
  47235. if (_this.pinchDeltaPercentage) {
  47236. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47237. }
  47238. else {
  47239. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47240. (_this.pinchPrecision *
  47241. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47242. direction);
  47243. }
  47244. if (_this.panningSensibility !== 0) {
  47245. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47246. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47247. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47248. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47249. previousMultiTouchPanPosition.x = pointersCenterX;
  47250. previousMultiTouchPanPosition.y = pointersCenterY;
  47251. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47252. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47253. }
  47254. }
  47255. else {
  47256. twoFingerActivityCount++;
  47257. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47258. if (_this.pinchDeltaPercentage) {
  47259. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47260. }
  47261. else {
  47262. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47263. (_this.pinchPrecision *
  47264. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47265. direction);
  47266. }
  47267. previousMultiTouchPanPosition.isPaning = false;
  47268. previousMultiTouchPanPosition.isPinching = true;
  47269. }
  47270. else {
  47271. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47272. if (!previousMultiTouchPanPosition.isPaning) {
  47273. previousMultiTouchPanPosition.isPaning = true;
  47274. previousMultiTouchPanPosition.isPinching = false;
  47275. previousMultiTouchPanPosition.x = ed.x;
  47276. previousMultiTouchPanPosition.y = ed.y;
  47277. return;
  47278. }
  47279. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47280. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47281. }
  47282. }
  47283. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47284. previousMultiTouchPanPosition.x = ed.x;
  47285. previousMultiTouchPanPosition.y = ed.y;
  47286. }
  47287. }
  47288. previousPinchSquaredDistance = pinchSquaredDistance;
  47289. }
  47290. }
  47291. };
  47292. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47293. this._onContextMenu = function (evt) {
  47294. evt.preventDefault();
  47295. };
  47296. if (!this.camera._useCtrlForPanning) {
  47297. element.addEventListener("contextmenu", this._onContextMenu, false);
  47298. }
  47299. this._onLostFocus = function () {
  47300. //this._keys = [];
  47301. pointA = pointB = null;
  47302. previousPinchSquaredDistance = 0;
  47303. previousMultiTouchPanPosition.isPaning = false;
  47304. previousMultiTouchPanPosition.isPinching = false;
  47305. twoFingerActivityCount = 0;
  47306. cacheSoloPointer = null;
  47307. initialDistance = 0;
  47308. };
  47309. this._onMouseMove = function (evt) {
  47310. if (!engine.isPointerLock) {
  47311. return;
  47312. }
  47313. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47314. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47315. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47316. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47317. if (!noPreventDefault) {
  47318. evt.preventDefault();
  47319. }
  47320. };
  47321. this._onGestureStart = function (e) {
  47322. if (window.MSGesture === undefined) {
  47323. return;
  47324. }
  47325. if (!_this._MSGestureHandler) {
  47326. _this._MSGestureHandler = new MSGesture();
  47327. _this._MSGestureHandler.target = element;
  47328. }
  47329. _this._MSGestureHandler.addPointer(e.pointerId);
  47330. };
  47331. this._onGesture = function (e) {
  47332. _this.camera.radius *= e.scale;
  47333. if (e.preventDefault) {
  47334. if (!noPreventDefault) {
  47335. e.stopPropagation();
  47336. e.preventDefault();
  47337. }
  47338. }
  47339. };
  47340. element.addEventListener("mousemove", this._onMouseMove, false);
  47341. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47342. element.addEventListener("MSGestureChange", this._onGesture, false);
  47343. BABYLON.Tools.RegisterTopRootEvents([
  47344. { name: "blur", handler: this._onLostFocus }
  47345. ]);
  47346. };
  47347. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47348. if (this._onLostFocus) {
  47349. BABYLON.Tools.UnregisterTopRootEvents([
  47350. { name: "blur", handler: this._onLostFocus }
  47351. ]);
  47352. }
  47353. if (element && this._observer) {
  47354. this.camera.getScene().onPointerObservable.remove(this._observer);
  47355. this._observer = null;
  47356. if (this._onContextMenu) {
  47357. element.removeEventListener("contextmenu", this._onContextMenu);
  47358. }
  47359. if (this._onMouseMove) {
  47360. element.removeEventListener("mousemove", this._onMouseMove);
  47361. }
  47362. if (this._onGestureStart) {
  47363. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47364. }
  47365. if (this._onGesture) {
  47366. element.removeEventListener("MSGestureChange", this._onGesture);
  47367. }
  47368. this._isPanClick = false;
  47369. this.pinchInwards = true;
  47370. this._onMouseMove = null;
  47371. this._onGestureStart = null;
  47372. this._onGesture = null;
  47373. this._MSGestureHandler = null;
  47374. this._onLostFocus = null;
  47375. this._onContextMenu = null;
  47376. }
  47377. };
  47378. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47379. return "ArcRotateCameraPointersInput";
  47380. };
  47381. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47382. return "pointers";
  47383. };
  47384. __decorate([
  47385. BABYLON.serialize()
  47386. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47387. __decorate([
  47388. BABYLON.serialize()
  47389. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47390. __decorate([
  47391. BABYLON.serialize()
  47392. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47393. __decorate([
  47394. BABYLON.serialize()
  47395. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47396. __decorate([
  47397. BABYLON.serialize()
  47398. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47399. __decorate([
  47400. BABYLON.serialize()
  47401. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47402. __decorate([
  47403. BABYLON.serialize()
  47404. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47405. __decorate([
  47406. BABYLON.serialize()
  47407. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47408. return ArcRotateCameraPointersInput;
  47409. }());
  47410. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47411. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47412. })(BABYLON || (BABYLON = {}));
  47413. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47414. var BABYLON;
  47415. (function (BABYLON) {
  47416. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47417. __extends(ArcRotateCameraInputsManager, _super);
  47418. function ArcRotateCameraInputsManager(camera) {
  47419. return _super.call(this, camera) || this;
  47420. }
  47421. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47422. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47423. return this;
  47424. };
  47425. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47426. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47427. return this;
  47428. };
  47429. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47430. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47431. return this;
  47432. };
  47433. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47434. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47435. return this;
  47436. };
  47437. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47438. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47439. return this;
  47440. };
  47441. return ArcRotateCameraInputsManager;
  47442. }(BABYLON.CameraInputsManager));
  47443. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47444. })(BABYLON || (BABYLON = {}));
  47445. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47446. var BABYLON;
  47447. (function (BABYLON) {
  47448. var ArcRotateCamera = /** @class */ (function (_super) {
  47449. __extends(ArcRotateCamera, _super);
  47450. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47451. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47452. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47453. _this.inertialAlphaOffset = 0;
  47454. _this.inertialBetaOffset = 0;
  47455. _this.inertialRadiusOffset = 0;
  47456. _this.lowerAlphaLimit = null;
  47457. _this.upperAlphaLimit = null;
  47458. _this.lowerBetaLimit = 0.01;
  47459. _this.upperBetaLimit = Math.PI;
  47460. _this.lowerRadiusLimit = null;
  47461. _this.upperRadiusLimit = null;
  47462. _this.inertialPanningX = 0;
  47463. _this.inertialPanningY = 0;
  47464. _this.pinchToPanMaxDistance = 20;
  47465. _this.panningDistanceLimit = null;
  47466. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47467. _this.panningInertia = 0.9;
  47468. //-- end properties for backward compatibility for inputs
  47469. _this.zoomOnFactor = 1;
  47470. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47471. _this.allowUpsideDown = true;
  47472. _this._viewMatrix = new BABYLON.Matrix();
  47473. // Panning
  47474. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47475. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47476. _this.checkCollisions = false;
  47477. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47478. _this._previousPosition = BABYLON.Vector3.Zero();
  47479. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47480. _this._newPosition = BABYLON.Vector3.Zero();
  47481. _this._computationVector = BABYLON.Vector3.Zero();
  47482. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47483. if (collidedMesh === void 0) { collidedMesh = null; }
  47484. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47485. newPosition.multiplyInPlace(_this._collider._radius);
  47486. }
  47487. if (!collidedMesh) {
  47488. _this._previousPosition.copyFrom(_this.position);
  47489. }
  47490. else {
  47491. _this.setPosition(newPosition);
  47492. if (_this.onCollide) {
  47493. _this.onCollide(collidedMesh);
  47494. }
  47495. }
  47496. // Recompute because of constraints
  47497. var cosa = Math.cos(_this.alpha);
  47498. var sina = Math.sin(_this.alpha);
  47499. var cosb = Math.cos(_this.beta);
  47500. var sinb = Math.sin(_this.beta);
  47501. if (sinb === 0) {
  47502. sinb = 0.0001;
  47503. }
  47504. var target = _this._getTargetPosition();
  47505. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47506. target.addToRef(_this._computationVector, _this._newPosition);
  47507. _this.position.copyFrom(_this._newPosition);
  47508. var up = _this.upVector;
  47509. if (_this.allowUpsideDown && _this.beta < 0) {
  47510. up = up.clone();
  47511. up = up.negate();
  47512. }
  47513. _this._computeViewMatrix(_this.position, target, up);
  47514. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47515. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47516. _this._collisionTriggered = false;
  47517. };
  47518. _this._target = BABYLON.Vector3.Zero();
  47519. if (target) {
  47520. _this.setTarget(target);
  47521. }
  47522. _this.alpha = alpha;
  47523. _this.beta = beta;
  47524. _this.radius = radius;
  47525. _this.getViewMatrix();
  47526. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47527. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47528. return _this;
  47529. }
  47530. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47531. get: function () {
  47532. return this._target;
  47533. },
  47534. set: function (value) {
  47535. this.setTarget(value);
  47536. },
  47537. enumerable: true,
  47538. configurable: true
  47539. });
  47540. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47541. //-- begin properties for backward compatibility for inputs
  47542. get: function () {
  47543. var pointers = this.inputs.attached["pointers"];
  47544. if (pointers)
  47545. return pointers.angularSensibilityX;
  47546. return 0;
  47547. },
  47548. set: function (value) {
  47549. var pointers = this.inputs.attached["pointers"];
  47550. if (pointers) {
  47551. pointers.angularSensibilityX = value;
  47552. }
  47553. },
  47554. enumerable: true,
  47555. configurable: true
  47556. });
  47557. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47558. get: function () {
  47559. var pointers = this.inputs.attached["pointers"];
  47560. if (pointers)
  47561. return pointers.angularSensibilityY;
  47562. return 0;
  47563. },
  47564. set: function (value) {
  47565. var pointers = this.inputs.attached["pointers"];
  47566. if (pointers) {
  47567. pointers.angularSensibilityY = value;
  47568. }
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47574. get: function () {
  47575. var pointers = this.inputs.attached["pointers"];
  47576. if (pointers)
  47577. return pointers.pinchPrecision;
  47578. return 0;
  47579. },
  47580. set: function (value) {
  47581. var pointers = this.inputs.attached["pointers"];
  47582. if (pointers) {
  47583. pointers.pinchPrecision = value;
  47584. }
  47585. },
  47586. enumerable: true,
  47587. configurable: true
  47588. });
  47589. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47590. get: function () {
  47591. var pointers = this.inputs.attached["pointers"];
  47592. if (pointers)
  47593. return pointers.pinchDeltaPercentage;
  47594. return 0;
  47595. },
  47596. set: function (value) {
  47597. var pointers = this.inputs.attached["pointers"];
  47598. if (pointers) {
  47599. pointers.pinchDeltaPercentage = value;
  47600. }
  47601. },
  47602. enumerable: true,
  47603. configurable: true
  47604. });
  47605. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47606. get: function () {
  47607. var pointers = this.inputs.attached["pointers"];
  47608. if (pointers)
  47609. return pointers.panningSensibility;
  47610. return 0;
  47611. },
  47612. set: function (value) {
  47613. var pointers = this.inputs.attached["pointers"];
  47614. if (pointers) {
  47615. pointers.panningSensibility = value;
  47616. }
  47617. },
  47618. enumerable: true,
  47619. configurable: true
  47620. });
  47621. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47622. get: function () {
  47623. var keyboard = this.inputs.attached["keyboard"];
  47624. if (keyboard)
  47625. return keyboard.keysUp;
  47626. return [];
  47627. },
  47628. set: function (value) {
  47629. var keyboard = this.inputs.attached["keyboard"];
  47630. if (keyboard)
  47631. keyboard.keysUp = value;
  47632. },
  47633. enumerable: true,
  47634. configurable: true
  47635. });
  47636. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47637. get: function () {
  47638. var keyboard = this.inputs.attached["keyboard"];
  47639. if (keyboard)
  47640. return keyboard.keysDown;
  47641. return [];
  47642. },
  47643. set: function (value) {
  47644. var keyboard = this.inputs.attached["keyboard"];
  47645. if (keyboard)
  47646. keyboard.keysDown = value;
  47647. },
  47648. enumerable: true,
  47649. configurable: true
  47650. });
  47651. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47652. get: function () {
  47653. var keyboard = this.inputs.attached["keyboard"];
  47654. if (keyboard)
  47655. return keyboard.keysLeft;
  47656. return [];
  47657. },
  47658. set: function (value) {
  47659. var keyboard = this.inputs.attached["keyboard"];
  47660. if (keyboard)
  47661. keyboard.keysLeft = value;
  47662. },
  47663. enumerable: true,
  47664. configurable: true
  47665. });
  47666. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47667. get: function () {
  47668. var keyboard = this.inputs.attached["keyboard"];
  47669. if (keyboard)
  47670. return keyboard.keysRight;
  47671. return [];
  47672. },
  47673. set: function (value) {
  47674. var keyboard = this.inputs.attached["keyboard"];
  47675. if (keyboard)
  47676. keyboard.keysRight = value;
  47677. },
  47678. enumerable: true,
  47679. configurable: true
  47680. });
  47681. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47682. get: function () {
  47683. var mousewheel = this.inputs.attached["mousewheel"];
  47684. if (mousewheel)
  47685. return mousewheel.wheelPrecision;
  47686. return 0;
  47687. },
  47688. set: function (value) {
  47689. var mousewheel = this.inputs.attached["mousewheel"];
  47690. if (mousewheel)
  47691. mousewheel.wheelPrecision = value;
  47692. },
  47693. enumerable: true,
  47694. configurable: true
  47695. });
  47696. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47697. get: function () {
  47698. var mousewheel = this.inputs.attached["mousewheel"];
  47699. if (mousewheel)
  47700. return mousewheel.wheelDeltaPercentage;
  47701. return 0;
  47702. },
  47703. set: function (value) {
  47704. var mousewheel = this.inputs.attached["mousewheel"];
  47705. if (mousewheel)
  47706. mousewheel.wheelDeltaPercentage = value;
  47707. },
  47708. enumerable: true,
  47709. configurable: true
  47710. });
  47711. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47712. get: function () {
  47713. return this._bouncingBehavior;
  47714. },
  47715. enumerable: true,
  47716. configurable: true
  47717. });
  47718. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47719. get: function () {
  47720. return this._bouncingBehavior != null;
  47721. },
  47722. set: function (value) {
  47723. if (value === this.useBouncingBehavior) {
  47724. return;
  47725. }
  47726. if (value) {
  47727. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47728. this.addBehavior(this._bouncingBehavior);
  47729. }
  47730. else if (this._bouncingBehavior) {
  47731. this.removeBehavior(this._bouncingBehavior);
  47732. this._bouncingBehavior = null;
  47733. }
  47734. },
  47735. enumerable: true,
  47736. configurable: true
  47737. });
  47738. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47739. get: function () {
  47740. return this._framingBehavior;
  47741. },
  47742. enumerable: true,
  47743. configurable: true
  47744. });
  47745. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47746. get: function () {
  47747. return this._framingBehavior != null;
  47748. },
  47749. set: function (value) {
  47750. if (value === this.useFramingBehavior) {
  47751. return;
  47752. }
  47753. if (value) {
  47754. this._framingBehavior = new BABYLON.FramingBehavior();
  47755. this.addBehavior(this._framingBehavior);
  47756. }
  47757. else if (this._framingBehavior) {
  47758. this.removeBehavior(this._framingBehavior);
  47759. this._framingBehavior = null;
  47760. }
  47761. },
  47762. enumerable: true,
  47763. configurable: true
  47764. });
  47765. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47766. get: function () {
  47767. return this._autoRotationBehavior;
  47768. },
  47769. enumerable: true,
  47770. configurable: true
  47771. });
  47772. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47773. get: function () {
  47774. return this._autoRotationBehavior != null;
  47775. },
  47776. set: function (value) {
  47777. if (value === this.useAutoRotationBehavior) {
  47778. return;
  47779. }
  47780. if (value) {
  47781. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47782. this.addBehavior(this._autoRotationBehavior);
  47783. }
  47784. else if (this._autoRotationBehavior) {
  47785. this.removeBehavior(this._autoRotationBehavior);
  47786. this._autoRotationBehavior = null;
  47787. }
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. // Cache
  47793. ArcRotateCamera.prototype._initCache = function () {
  47794. _super.prototype._initCache.call(this);
  47795. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47796. this._cache.alpha = undefined;
  47797. this._cache.beta = undefined;
  47798. this._cache.radius = undefined;
  47799. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47800. };
  47801. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47802. if (!ignoreParentClass) {
  47803. _super.prototype._updateCache.call(this);
  47804. }
  47805. this._cache._target.copyFrom(this._getTargetPosition());
  47806. this._cache.alpha = this.alpha;
  47807. this._cache.beta = this.beta;
  47808. this._cache.radius = this.radius;
  47809. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47810. };
  47811. ArcRotateCamera.prototype._getTargetPosition = function () {
  47812. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47813. var pos = this._targetHost.getAbsolutePosition();
  47814. if (this._targetBoundingCenter) {
  47815. pos.addToRef(this._targetBoundingCenter, this._target);
  47816. }
  47817. else {
  47818. this._target.copyFrom(pos);
  47819. }
  47820. }
  47821. var lockedTargetPosition = this._getLockedTargetPosition();
  47822. if (lockedTargetPosition) {
  47823. return lockedTargetPosition;
  47824. }
  47825. return this._target;
  47826. };
  47827. ArcRotateCamera.prototype.storeState = function () {
  47828. this._storedAlpha = this.alpha;
  47829. this._storedBeta = this.beta;
  47830. this._storedRadius = this.radius;
  47831. this._storedTarget = this._getTargetPosition().clone();
  47832. return _super.prototype.storeState.call(this);
  47833. };
  47834. /**
  47835. * Restored camera state. You must call storeState() first
  47836. */
  47837. ArcRotateCamera.prototype._restoreStateValues = function () {
  47838. if (!_super.prototype._restoreStateValues.call(this)) {
  47839. return false;
  47840. }
  47841. this.alpha = this._storedAlpha;
  47842. this.beta = this._storedBeta;
  47843. this.radius = this._storedRadius;
  47844. this.setTarget(this._storedTarget.clone());
  47845. this.inertialAlphaOffset = 0;
  47846. this.inertialBetaOffset = 0;
  47847. this.inertialRadiusOffset = 0;
  47848. this.inertialPanningX = 0;
  47849. this.inertialPanningY = 0;
  47850. return true;
  47851. };
  47852. // Synchronized
  47853. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47854. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47855. return false;
  47856. return this._cache._target.equals(this._getTargetPosition())
  47857. && this._cache.alpha === this.alpha
  47858. && this._cache.beta === this.beta
  47859. && this._cache.radius === this.radius
  47860. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47861. };
  47862. // Methods
  47863. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47864. var _this = this;
  47865. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47866. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47867. this._useCtrlForPanning = useCtrlForPanning;
  47868. this._panningMouseButton = panningMouseButton;
  47869. this.inputs.attachElement(element, noPreventDefault);
  47870. this._reset = function () {
  47871. _this.inertialAlphaOffset = 0;
  47872. _this.inertialBetaOffset = 0;
  47873. _this.inertialRadiusOffset = 0;
  47874. _this.inertialPanningX = 0;
  47875. _this.inertialPanningY = 0;
  47876. };
  47877. };
  47878. ArcRotateCamera.prototype.detachControl = function (element) {
  47879. this.inputs.detachElement(element);
  47880. if (this._reset) {
  47881. this._reset();
  47882. }
  47883. };
  47884. ArcRotateCamera.prototype._checkInputs = function () {
  47885. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47886. if (this._collisionTriggered) {
  47887. return;
  47888. }
  47889. this.inputs.checkInputs();
  47890. // Inertia
  47891. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47892. var inertialAlphaOffset = this.inertialAlphaOffset;
  47893. if (this.beta <= 0)
  47894. inertialAlphaOffset *= -1;
  47895. if (this.getScene().useRightHandedSystem)
  47896. inertialAlphaOffset *= -1;
  47897. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47898. inertialAlphaOffset *= -1;
  47899. this.alpha += inertialAlphaOffset;
  47900. this.beta += this.inertialBetaOffset;
  47901. this.radius -= this.inertialRadiusOffset;
  47902. this.inertialAlphaOffset *= this.inertia;
  47903. this.inertialBetaOffset *= this.inertia;
  47904. this.inertialRadiusOffset *= this.inertia;
  47905. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47906. this.inertialAlphaOffset = 0;
  47907. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47908. this.inertialBetaOffset = 0;
  47909. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47910. this.inertialRadiusOffset = 0;
  47911. }
  47912. // Panning inertia
  47913. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47914. if (!this._localDirection) {
  47915. this._localDirection = BABYLON.Vector3.Zero();
  47916. this._transformedDirection = BABYLON.Vector3.Zero();
  47917. }
  47918. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47919. this._localDirection.multiplyInPlace(this.panningAxis);
  47920. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47921. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47922. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47923. if (!this.panningAxis.y) {
  47924. this._transformedDirection.y = 0;
  47925. }
  47926. if (!this._targetHost) {
  47927. if (this.panningDistanceLimit) {
  47928. this._transformedDirection.addInPlace(this._target);
  47929. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47930. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47931. this._target.copyFrom(this._transformedDirection);
  47932. }
  47933. }
  47934. else {
  47935. this._target.addInPlace(this._transformedDirection);
  47936. }
  47937. }
  47938. this.inertialPanningX *= this.panningInertia;
  47939. this.inertialPanningY *= this.panningInertia;
  47940. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47941. this.inertialPanningX = 0;
  47942. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47943. this.inertialPanningY = 0;
  47944. }
  47945. // Limits
  47946. this._checkLimits();
  47947. _super.prototype._checkInputs.call(this);
  47948. };
  47949. ArcRotateCamera.prototype._checkLimits = function () {
  47950. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47951. if (this.allowUpsideDown && this.beta > Math.PI) {
  47952. this.beta = this.beta - (2 * Math.PI);
  47953. }
  47954. }
  47955. else {
  47956. if (this.beta < this.lowerBetaLimit) {
  47957. this.beta = this.lowerBetaLimit;
  47958. }
  47959. }
  47960. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47961. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47962. this.beta = this.beta + (2 * Math.PI);
  47963. }
  47964. }
  47965. else {
  47966. if (this.beta > this.upperBetaLimit) {
  47967. this.beta = this.upperBetaLimit;
  47968. }
  47969. }
  47970. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47971. this.alpha = this.lowerAlphaLimit;
  47972. }
  47973. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47974. this.alpha = this.upperAlphaLimit;
  47975. }
  47976. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47977. this.radius = this.lowerRadiusLimit;
  47978. }
  47979. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47980. this.radius = this.upperRadiusLimit;
  47981. }
  47982. };
  47983. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47984. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47985. this.radius = this._computationVector.length();
  47986. if (this.radius === 0) {
  47987. this.radius = 0.0001; // Just to avoid division by zero
  47988. }
  47989. // Alpha
  47990. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47991. if (this._computationVector.z < 0) {
  47992. this.alpha = 2 * Math.PI - this.alpha;
  47993. }
  47994. // Beta
  47995. this.beta = Math.acos(this._computationVector.y / this.radius);
  47996. this._checkLimits();
  47997. };
  47998. ArcRotateCamera.prototype.setPosition = function (position) {
  47999. if (this.position.equals(position)) {
  48000. return;
  48001. }
  48002. this.position.copyFrom(position);
  48003. this.rebuildAnglesAndRadius();
  48004. };
  48005. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48006. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48007. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48008. if (target.getBoundingInfo) {
  48009. if (toBoundingCenter) {
  48010. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48011. }
  48012. else {
  48013. this._targetBoundingCenter = null;
  48014. }
  48015. this._targetHost = target;
  48016. this._target = this._getTargetPosition();
  48017. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48018. }
  48019. else {
  48020. var newTarget = target;
  48021. var currentTarget = this._getTargetPosition();
  48022. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48023. return;
  48024. }
  48025. this._targetHost = null;
  48026. this._target = newTarget;
  48027. this._targetBoundingCenter = null;
  48028. this.onMeshTargetChangedObservable.notifyObservers(null);
  48029. }
  48030. this.rebuildAnglesAndRadius();
  48031. };
  48032. ArcRotateCamera.prototype._getViewMatrix = function () {
  48033. // Compute
  48034. var cosa = Math.cos(this.alpha);
  48035. var sina = Math.sin(this.alpha);
  48036. var cosb = Math.cos(this.beta);
  48037. var sinb = Math.sin(this.beta);
  48038. if (sinb === 0) {
  48039. sinb = 0.0001;
  48040. }
  48041. var target = this._getTargetPosition();
  48042. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48043. target.addToRef(this._computationVector, this._newPosition);
  48044. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48045. if (!this._collider) {
  48046. this._collider = new BABYLON.Collider();
  48047. }
  48048. this._collider._radius = this.collisionRadius;
  48049. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48050. this._collisionTriggered = true;
  48051. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48052. }
  48053. else {
  48054. this.position.copyFrom(this._newPosition);
  48055. var up = this.upVector;
  48056. if (this.allowUpsideDown && sinb < 0) {
  48057. up = up.clone();
  48058. up = up.negate();
  48059. }
  48060. this._computeViewMatrix(this.position, target, up);
  48061. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48062. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48063. }
  48064. this._currentTarget = target;
  48065. return this._viewMatrix;
  48066. };
  48067. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48068. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48069. meshes = meshes || this.getScene().meshes;
  48070. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48071. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48072. this.radius = distance * this.zoomOnFactor;
  48073. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48074. };
  48075. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48076. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48077. var meshesOrMinMaxVector;
  48078. var distance;
  48079. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48080. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48081. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48082. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48083. }
  48084. else { //minMaxVector and distance
  48085. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48086. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48087. distance = minMaxVectorAndDistance.distance;
  48088. }
  48089. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48090. if (!doNotUpdateMaxZ) {
  48091. this.maxZ = distance * 2;
  48092. }
  48093. };
  48094. /**
  48095. * @override
  48096. * Override Camera.createRigCamera
  48097. */
  48098. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48099. var alphaShift = 0;
  48100. switch (this.cameraRigMode) {
  48101. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48102. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48103. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48104. case BABYLON.Camera.RIG_MODE_VR:
  48105. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48106. break;
  48107. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48108. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48109. break;
  48110. }
  48111. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48112. rigCam._cameraRigParams = {};
  48113. return rigCam;
  48114. };
  48115. /**
  48116. * @override
  48117. * Override Camera._updateRigCameras
  48118. */
  48119. ArcRotateCamera.prototype._updateRigCameras = function () {
  48120. var camLeft = this._rigCameras[0];
  48121. var camRight = this._rigCameras[1];
  48122. camLeft.beta = camRight.beta = this.beta;
  48123. camLeft.radius = camRight.radius = this.radius;
  48124. switch (this.cameraRigMode) {
  48125. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48126. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48127. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48128. case BABYLON.Camera.RIG_MODE_VR:
  48129. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48130. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48131. break;
  48132. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48133. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48134. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48135. break;
  48136. }
  48137. _super.prototype._updateRigCameras.call(this);
  48138. };
  48139. ArcRotateCamera.prototype.dispose = function () {
  48140. this.inputs.clear();
  48141. _super.prototype.dispose.call(this);
  48142. };
  48143. ArcRotateCamera.prototype.getClassName = function () {
  48144. return "ArcRotateCamera";
  48145. };
  48146. __decorate([
  48147. BABYLON.serialize()
  48148. ], ArcRotateCamera.prototype, "alpha", void 0);
  48149. __decorate([
  48150. BABYLON.serialize()
  48151. ], ArcRotateCamera.prototype, "beta", void 0);
  48152. __decorate([
  48153. BABYLON.serialize()
  48154. ], ArcRotateCamera.prototype, "radius", void 0);
  48155. __decorate([
  48156. BABYLON.serializeAsVector3("target")
  48157. ], ArcRotateCamera.prototype, "_target", void 0);
  48158. __decorate([
  48159. BABYLON.serialize()
  48160. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48161. __decorate([
  48162. BABYLON.serialize()
  48163. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48164. __decorate([
  48165. BABYLON.serialize()
  48166. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48170. __decorate([
  48171. BABYLON.serialize()
  48172. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48173. __decorate([
  48174. BABYLON.serialize()
  48175. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48176. __decorate([
  48177. BABYLON.serialize()
  48178. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48179. __decorate([
  48180. BABYLON.serialize()
  48181. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48182. __decorate([
  48183. BABYLON.serialize()
  48184. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48185. __decorate([
  48186. BABYLON.serialize()
  48187. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48188. __decorate([
  48189. BABYLON.serialize()
  48190. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48191. __decorate([
  48192. BABYLON.serialize()
  48193. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48194. __decorate([
  48195. BABYLON.serialize()
  48196. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48197. __decorate([
  48198. BABYLON.serializeAsVector3()
  48199. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48200. __decorate([
  48201. BABYLON.serialize()
  48202. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48209. return ArcRotateCamera;
  48210. }(BABYLON.TargetCamera));
  48211. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48212. })(BABYLON || (BABYLON = {}));
  48213. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48214. var BABYLON;
  48215. (function (BABYLON) {
  48216. /**
  48217. * The HemisphericLight simulates the ambient environment light,
  48218. * so the passed direction is the light reflection direction, not the incoming direction.
  48219. */
  48220. var HemisphericLight = /** @class */ (function (_super) {
  48221. __extends(HemisphericLight, _super);
  48222. /**
  48223. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48224. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48225. * The HemisphericLight can't cast shadows.
  48226. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48227. * @param name The friendly name of the light
  48228. * @param direction The direction of the light reflection
  48229. * @param scene The scene the light belongs to
  48230. */
  48231. function HemisphericLight(name, direction, scene) {
  48232. var _this = _super.call(this, name, scene) || this;
  48233. /**
  48234. * The groundColor is the light in the opposite direction to the one specified during creation.
  48235. * 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.
  48236. */
  48237. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48238. _this.direction = direction || BABYLON.Vector3.Up();
  48239. return _this;
  48240. }
  48241. HemisphericLight.prototype._buildUniformLayout = function () {
  48242. this._uniformBuffer.addUniform("vLightData", 4);
  48243. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48244. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48245. this._uniformBuffer.addUniform("vLightGround", 3);
  48246. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48247. this._uniformBuffer.addUniform("depthValues", 2);
  48248. this._uniformBuffer.create();
  48249. };
  48250. /**
  48251. * Returns the string "HemisphericLight".
  48252. * @return The class name
  48253. */
  48254. HemisphericLight.prototype.getClassName = function () {
  48255. return "HemisphericLight";
  48256. };
  48257. /**
  48258. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48259. * Returns the updated direction.
  48260. * @param target The target the direction should point to
  48261. * @return The computed direction
  48262. */
  48263. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48264. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48265. return this.direction;
  48266. };
  48267. /**
  48268. * Returns the shadow generator associated to the light.
  48269. * @returns Always null for hemispheric lights because it does not support shadows.
  48270. */
  48271. HemisphericLight.prototype.getShadowGenerator = function () {
  48272. return null;
  48273. };
  48274. /**
  48275. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48276. * @param effect The effect to update
  48277. * @param lightIndex The index of the light in the effect to update
  48278. * @returns The hemispheric light
  48279. */
  48280. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48281. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48282. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48283. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48284. return this;
  48285. };
  48286. /**
  48287. * @hidden internal use only.
  48288. */
  48289. HemisphericLight.prototype._getWorldMatrix = function () {
  48290. if (!this._worldMatrix) {
  48291. this._worldMatrix = BABYLON.Matrix.Identity();
  48292. }
  48293. return this._worldMatrix;
  48294. };
  48295. /**
  48296. * Returns the integer 3.
  48297. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48298. */
  48299. HemisphericLight.prototype.getTypeID = function () {
  48300. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48301. };
  48302. __decorate([
  48303. BABYLON.serializeAsColor3()
  48304. ], HemisphericLight.prototype, "groundColor", void 0);
  48305. __decorate([
  48306. BABYLON.serializeAsVector3()
  48307. ], HemisphericLight.prototype, "direction", void 0);
  48308. return HemisphericLight;
  48309. }(BABYLON.Light));
  48310. BABYLON.HemisphericLight = HemisphericLight;
  48311. })(BABYLON || (BABYLON = {}));
  48312. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48313. var BABYLON;
  48314. (function (BABYLON) {
  48315. /**
  48316. * Base implementation IShadowLight
  48317. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48318. */
  48319. var ShadowLight = /** @class */ (function (_super) {
  48320. __extends(ShadowLight, _super);
  48321. function ShadowLight() {
  48322. var _this = _super !== null && _super.apply(this, arguments) || this;
  48323. _this._needProjectionMatrixCompute = true;
  48324. return _this;
  48325. }
  48326. ShadowLight.prototype._setPosition = function (value) {
  48327. this._position = value;
  48328. };
  48329. Object.defineProperty(ShadowLight.prototype, "position", {
  48330. /**
  48331. * Sets the position the shadow will be casted from. Also use as the light position for both
  48332. * point and spot lights.
  48333. */
  48334. get: function () {
  48335. return this._position;
  48336. },
  48337. /**
  48338. * Sets the position the shadow will be casted from. Also use as the light position for both
  48339. * point and spot lights.
  48340. */
  48341. set: function (value) {
  48342. this._setPosition(value);
  48343. },
  48344. enumerable: true,
  48345. configurable: true
  48346. });
  48347. ShadowLight.prototype._setDirection = function (value) {
  48348. this._direction = value;
  48349. };
  48350. Object.defineProperty(ShadowLight.prototype, "direction", {
  48351. /**
  48352. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48353. * Also use as the light direction on spot and directional lights.
  48354. */
  48355. get: function () {
  48356. return this._direction;
  48357. },
  48358. /**
  48359. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48360. * Also use as the light direction on spot and directional lights.
  48361. */
  48362. set: function (value) {
  48363. this._setDirection(value);
  48364. },
  48365. enumerable: true,
  48366. configurable: true
  48367. });
  48368. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48369. /**
  48370. * Gets the shadow projection clipping minimum z value.
  48371. */
  48372. get: function () {
  48373. return this._shadowMinZ;
  48374. },
  48375. /**
  48376. * Sets the shadow projection clipping minimum z value.
  48377. */
  48378. set: function (value) {
  48379. this._shadowMinZ = value;
  48380. this.forceProjectionMatrixCompute();
  48381. },
  48382. enumerable: true,
  48383. configurable: true
  48384. });
  48385. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48386. /**
  48387. * Sets the shadow projection clipping maximum z value.
  48388. */
  48389. get: function () {
  48390. return this._shadowMaxZ;
  48391. },
  48392. /**
  48393. * Gets the shadow projection clipping maximum z value.
  48394. */
  48395. set: function (value) {
  48396. this._shadowMaxZ = value;
  48397. this.forceProjectionMatrixCompute();
  48398. },
  48399. enumerable: true,
  48400. configurable: true
  48401. });
  48402. /**
  48403. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48404. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48405. */
  48406. ShadowLight.prototype.computeTransformedInformation = function () {
  48407. if (this.parent && this.parent.getWorldMatrix) {
  48408. if (!this.transformedPosition) {
  48409. this.transformedPosition = BABYLON.Vector3.Zero();
  48410. }
  48411. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48412. // In case the direction is present.
  48413. if (this.direction) {
  48414. if (!this.transformedDirection) {
  48415. this.transformedDirection = BABYLON.Vector3.Zero();
  48416. }
  48417. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48418. }
  48419. return true;
  48420. }
  48421. return false;
  48422. };
  48423. /**
  48424. * Return the depth scale used for the shadow map.
  48425. * @returns the depth scale.
  48426. */
  48427. ShadowLight.prototype.getDepthScale = function () {
  48428. return 50.0;
  48429. };
  48430. /**
  48431. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48432. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48433. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48434. */
  48435. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48436. return this.transformedDirection ? this.transformedDirection : this.direction;
  48437. };
  48438. /**
  48439. * Returns the ShadowLight absolute position in the World.
  48440. * @returns the position vector in world space
  48441. */
  48442. ShadowLight.prototype.getAbsolutePosition = function () {
  48443. return this.transformedPosition ? this.transformedPosition : this.position;
  48444. };
  48445. /**
  48446. * Sets the ShadowLight direction toward the passed target.
  48447. * @param target The point tot target in local space
  48448. * @returns the updated ShadowLight direction
  48449. */
  48450. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48451. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48452. return this.direction;
  48453. };
  48454. /**
  48455. * Returns the light rotation in euler definition.
  48456. * @returns the x y z rotation in local space.
  48457. */
  48458. ShadowLight.prototype.getRotation = function () {
  48459. this.direction.normalize();
  48460. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48461. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48462. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48463. };
  48464. /**
  48465. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48466. * @returns true if a cube texture needs to be use
  48467. */
  48468. ShadowLight.prototype.needCube = function () {
  48469. return false;
  48470. };
  48471. /**
  48472. * Detects if the projection matrix requires to be recomputed this frame.
  48473. * @returns true if it requires to be recomputed otherwise, false.
  48474. */
  48475. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48476. return this._needProjectionMatrixCompute;
  48477. };
  48478. /**
  48479. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48480. */
  48481. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48482. this._needProjectionMatrixCompute = true;
  48483. };
  48484. /**
  48485. * Get the world matrix of the sahdow lights.
  48486. * @hidden Internal Use Only
  48487. */
  48488. ShadowLight.prototype._getWorldMatrix = function () {
  48489. if (!this._worldMatrix) {
  48490. this._worldMatrix = BABYLON.Matrix.Identity();
  48491. }
  48492. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48493. return this._worldMatrix;
  48494. };
  48495. /**
  48496. * Gets the minZ used for shadow according to both the scene and the light.
  48497. * @param activeCamera The camera we are returning the min for
  48498. * @returns the depth min z
  48499. */
  48500. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48501. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48502. };
  48503. /**
  48504. * Gets the maxZ used for shadow according to both the scene and the light.
  48505. * @param activeCamera The camera we are returning the max for
  48506. * @returns the depth max z
  48507. */
  48508. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48509. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48510. };
  48511. /**
  48512. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48513. * @param matrix The materix to updated with the projection information
  48514. * @param viewMatrix The transform matrix of the light
  48515. * @param renderList The list of mesh to render in the map
  48516. * @returns The current light
  48517. */
  48518. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48519. if (this.customProjectionMatrixBuilder) {
  48520. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48521. }
  48522. else {
  48523. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48524. }
  48525. return this;
  48526. };
  48527. __decorate([
  48528. BABYLON.serializeAsVector3()
  48529. ], ShadowLight.prototype, "position", null);
  48530. __decorate([
  48531. BABYLON.serializeAsVector3()
  48532. ], ShadowLight.prototype, "direction", null);
  48533. __decorate([
  48534. BABYLON.serialize()
  48535. ], ShadowLight.prototype, "shadowMinZ", null);
  48536. __decorate([
  48537. BABYLON.serialize()
  48538. ], ShadowLight.prototype, "shadowMaxZ", null);
  48539. return ShadowLight;
  48540. }(BABYLON.Light));
  48541. BABYLON.ShadowLight = ShadowLight;
  48542. })(BABYLON || (BABYLON = {}));
  48543. //# sourceMappingURL=babylon.shadowLight.js.map
  48544. var BABYLON;
  48545. (function (BABYLON) {
  48546. /**
  48547. * A point light is a light defined by an unique point in world space.
  48548. * The light is emitted in every direction from this point.
  48549. * A good example of a point light is a standard light bulb.
  48550. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48551. */
  48552. var PointLight = /** @class */ (function (_super) {
  48553. __extends(PointLight, _super);
  48554. /**
  48555. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48556. * A PointLight emits the light in every direction.
  48557. * It can cast shadows.
  48558. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48559. * ```javascript
  48560. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48561. * ```
  48562. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48563. * @param name The light friendly name
  48564. * @param position The position of the point light in the scene
  48565. * @param scene The scene the lights belongs to
  48566. */
  48567. function PointLight(name, position, scene) {
  48568. var _this = _super.call(this, name, scene) || this;
  48569. _this._shadowAngle = Math.PI / 2;
  48570. _this.position = position;
  48571. return _this;
  48572. }
  48573. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48574. /**
  48575. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48576. * This specifies what angle the shadow will use to be created.
  48577. *
  48578. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48579. */
  48580. get: function () {
  48581. return this._shadowAngle;
  48582. },
  48583. /**
  48584. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48585. * This specifies what angle the shadow will use to be created.
  48586. *
  48587. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48588. */
  48589. set: function (value) {
  48590. this._shadowAngle = value;
  48591. this.forceProjectionMatrixCompute();
  48592. },
  48593. enumerable: true,
  48594. configurable: true
  48595. });
  48596. Object.defineProperty(PointLight.prototype, "direction", {
  48597. /**
  48598. * Gets the direction if it has been set.
  48599. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48600. */
  48601. get: function () {
  48602. return this._direction;
  48603. },
  48604. /**
  48605. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48606. */
  48607. set: function (value) {
  48608. var previousNeedCube = this.needCube();
  48609. this._direction = value;
  48610. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48611. this._shadowGenerator.recreateShadowMap();
  48612. }
  48613. },
  48614. enumerable: true,
  48615. configurable: true
  48616. });
  48617. /**
  48618. * Returns the string "PointLight"
  48619. * @returns the class name
  48620. */
  48621. PointLight.prototype.getClassName = function () {
  48622. return "PointLight";
  48623. };
  48624. /**
  48625. * Returns the integer 0.
  48626. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48627. */
  48628. PointLight.prototype.getTypeID = function () {
  48629. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48630. };
  48631. /**
  48632. * Specifies wether or not the shadowmap should be a cube texture.
  48633. * @returns true if the shadowmap needs to be a cube texture.
  48634. */
  48635. PointLight.prototype.needCube = function () {
  48636. return !this.direction;
  48637. };
  48638. /**
  48639. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48640. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48641. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48642. */
  48643. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48644. if (this.direction) {
  48645. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48646. }
  48647. else {
  48648. switch (faceIndex) {
  48649. case 0:
  48650. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48651. case 1:
  48652. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48653. case 2:
  48654. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48655. case 3:
  48656. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48657. case 4:
  48658. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48659. case 5:
  48660. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48661. }
  48662. }
  48663. return BABYLON.Vector3.Zero();
  48664. };
  48665. /**
  48666. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48667. * - fov = PI / 2
  48668. * - aspect ratio : 1.0
  48669. * - z-near and far equal to the active camera minZ and maxZ.
  48670. * Returns the PointLight.
  48671. */
  48672. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48673. var activeCamera = this.getScene().activeCamera;
  48674. if (!activeCamera) {
  48675. return;
  48676. }
  48677. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48678. };
  48679. PointLight.prototype._buildUniformLayout = function () {
  48680. this._uniformBuffer.addUniform("vLightData", 4);
  48681. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48682. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48683. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48684. this._uniformBuffer.addUniform("depthValues", 2);
  48685. this._uniformBuffer.create();
  48686. };
  48687. /**
  48688. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48689. * @param effect The effect to update
  48690. * @param lightIndex The index of the light in the effect to update
  48691. * @returns The point light
  48692. */
  48693. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48694. if (this.computeTransformedInformation()) {
  48695. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48696. return this;
  48697. }
  48698. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48699. return this;
  48700. };
  48701. __decorate([
  48702. BABYLON.serialize()
  48703. ], PointLight.prototype, "shadowAngle", null);
  48704. return PointLight;
  48705. }(BABYLON.ShadowLight));
  48706. BABYLON.PointLight = PointLight;
  48707. })(BABYLON || (BABYLON = {}));
  48708. //# sourceMappingURL=babylon.pointLight.js.map
  48709. var BABYLON;
  48710. (function (BABYLON) {
  48711. /**
  48712. * A directional light is defined by a direction (what a surprise!).
  48713. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48714. * 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.
  48715. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48716. */
  48717. var DirectionalLight = /** @class */ (function (_super) {
  48718. __extends(DirectionalLight, _super);
  48719. /**
  48720. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48721. * The directional light is emitted from everywhere in the given direction.
  48722. * It can cast shawdows.
  48723. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48724. * @param name The friendly name of the light
  48725. * @param direction The direction of the light
  48726. * @param scene The scene the light belongs to
  48727. */
  48728. function DirectionalLight(name, direction, scene) {
  48729. var _this = _super.call(this, name, scene) || this;
  48730. _this._shadowFrustumSize = 0;
  48731. _this._shadowOrthoScale = 0.1;
  48732. /**
  48733. * Automatically compute the projection matrix to best fit (including all the casters)
  48734. * on each frame.
  48735. */
  48736. _this.autoUpdateExtends = true;
  48737. // Cache
  48738. _this._orthoLeft = Number.MAX_VALUE;
  48739. _this._orthoRight = Number.MIN_VALUE;
  48740. _this._orthoTop = Number.MIN_VALUE;
  48741. _this._orthoBottom = Number.MAX_VALUE;
  48742. _this.position = direction.scale(-1.0);
  48743. _this.direction = direction;
  48744. return _this;
  48745. }
  48746. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48747. /**
  48748. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48749. */
  48750. get: function () {
  48751. return this._shadowFrustumSize;
  48752. },
  48753. /**
  48754. * Specifies a fix frustum size for the shadow generation.
  48755. */
  48756. set: function (value) {
  48757. this._shadowFrustumSize = value;
  48758. this.forceProjectionMatrixCompute();
  48759. },
  48760. enumerable: true,
  48761. configurable: true
  48762. });
  48763. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48764. /**
  48765. * Gets the shadow projection scale against the optimal computed one.
  48766. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48767. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48768. */
  48769. get: function () {
  48770. return this._shadowOrthoScale;
  48771. },
  48772. /**
  48773. * Sets the shadow projection scale against the optimal computed one.
  48774. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48775. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48776. */
  48777. set: function (value) {
  48778. this._shadowOrthoScale = value;
  48779. this.forceProjectionMatrixCompute();
  48780. },
  48781. enumerable: true,
  48782. configurable: true
  48783. });
  48784. /**
  48785. * Returns the string "DirectionalLight".
  48786. * @return The class name
  48787. */
  48788. DirectionalLight.prototype.getClassName = function () {
  48789. return "DirectionalLight";
  48790. };
  48791. /**
  48792. * Returns the integer 1.
  48793. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48794. */
  48795. DirectionalLight.prototype.getTypeID = function () {
  48796. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48797. };
  48798. /**
  48799. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48800. * Returns the DirectionalLight Shadow projection matrix.
  48801. */
  48802. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48803. if (this.shadowFrustumSize > 0) {
  48804. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48805. }
  48806. else {
  48807. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48808. }
  48809. };
  48810. /**
  48811. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48812. * Returns the DirectionalLight Shadow projection matrix.
  48813. */
  48814. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48815. var activeCamera = this.getScene().activeCamera;
  48816. if (!activeCamera) {
  48817. return;
  48818. }
  48819. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48820. };
  48821. /**
  48822. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48823. * Returns the DirectionalLight Shadow projection matrix.
  48824. */
  48825. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48826. var activeCamera = this.getScene().activeCamera;
  48827. if (!activeCamera) {
  48828. return;
  48829. }
  48830. // Check extends
  48831. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48832. var tempVector3 = BABYLON.Vector3.Zero();
  48833. this._orthoLeft = Number.MAX_VALUE;
  48834. this._orthoRight = Number.MIN_VALUE;
  48835. this._orthoTop = Number.MIN_VALUE;
  48836. this._orthoBottom = Number.MAX_VALUE;
  48837. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48838. var mesh = renderList[meshIndex];
  48839. if (!mesh) {
  48840. continue;
  48841. }
  48842. var boundingInfo = mesh.getBoundingInfo();
  48843. var boundingBox = boundingInfo.boundingBox;
  48844. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48845. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48846. if (tempVector3.x < this._orthoLeft)
  48847. this._orthoLeft = tempVector3.x;
  48848. if (tempVector3.y < this._orthoBottom)
  48849. this._orthoBottom = tempVector3.y;
  48850. if (tempVector3.x > this._orthoRight)
  48851. this._orthoRight = tempVector3.x;
  48852. if (tempVector3.y > this._orthoTop)
  48853. this._orthoTop = tempVector3.y;
  48854. }
  48855. }
  48856. }
  48857. var xOffset = this._orthoRight - this._orthoLeft;
  48858. var yOffset = this._orthoTop - this._orthoBottom;
  48859. 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);
  48860. };
  48861. DirectionalLight.prototype._buildUniformLayout = function () {
  48862. this._uniformBuffer.addUniform("vLightData", 4);
  48863. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48864. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48865. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48866. this._uniformBuffer.addUniform("depthValues", 2);
  48867. this._uniformBuffer.create();
  48868. };
  48869. /**
  48870. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48871. * @param effect The effect to update
  48872. * @param lightIndex The index of the light in the effect to update
  48873. * @returns The directional light
  48874. */
  48875. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48876. if (this.computeTransformedInformation()) {
  48877. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48878. return this;
  48879. }
  48880. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48881. return this;
  48882. };
  48883. /**
  48884. * Gets the minZ used for shadow according to both the scene and the light.
  48885. *
  48886. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48887. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48888. * @param activeCamera The camera we are returning the min for
  48889. * @returns the depth min z
  48890. */
  48891. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48892. return 1;
  48893. };
  48894. /**
  48895. * Gets the maxZ used for shadow according to both the scene and the light.
  48896. *
  48897. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48898. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48899. * @param activeCamera The camera we are returning the max for
  48900. * @returns the depth max z
  48901. */
  48902. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48903. return 1;
  48904. };
  48905. __decorate([
  48906. BABYLON.serialize()
  48907. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48908. __decorate([
  48909. BABYLON.serialize()
  48910. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48911. __decorate([
  48912. BABYLON.serialize()
  48913. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48914. return DirectionalLight;
  48915. }(BABYLON.ShadowLight));
  48916. BABYLON.DirectionalLight = DirectionalLight;
  48917. })(BABYLON || (BABYLON = {}));
  48918. //# sourceMappingURL=babylon.directionalLight.js.map
  48919. var BABYLON;
  48920. (function (BABYLON) {
  48921. /**
  48922. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48923. * These values define a cone of light starting from the position, emitting toward the direction.
  48924. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48925. * and the exponent defines the speed of the decay of the light with distance (reach).
  48926. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48927. */
  48928. var SpotLight = /** @class */ (function (_super) {
  48929. __extends(SpotLight, _super);
  48930. /**
  48931. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48932. * It can cast shadows.
  48933. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48934. * @param name The light friendly name
  48935. * @param position The position of the spot light in the scene
  48936. * @param direction The direction of the light in the scene
  48937. * @param angle The cone angle of the light in Radians
  48938. * @param exponent The light decay speed with the distance from the emission spot
  48939. * @param scene The scene the lights belongs to
  48940. */
  48941. function SpotLight(name, position, direction, angle, exponent, scene) {
  48942. var _this = _super.call(this, name, scene) || this;
  48943. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48944. _this._projectionTextureLightNear = 1e-6;
  48945. _this._projectionTextureLightFar = 1000.0;
  48946. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48947. _this._projectionTextureViewLightDirty = true;
  48948. _this._projectionTextureProjectionLightDirty = true;
  48949. _this._projectionTextureDirty = true;
  48950. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48951. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48952. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48953. _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);
  48954. _this.position = position;
  48955. _this.direction = direction;
  48956. _this.angle = angle;
  48957. _this.exponent = exponent;
  48958. return _this;
  48959. }
  48960. Object.defineProperty(SpotLight.prototype, "angle", {
  48961. /**
  48962. * Gets the cone angle of the spot light in Radians.
  48963. */
  48964. get: function () {
  48965. return this._angle;
  48966. },
  48967. /**
  48968. * Sets the cone angle of the spot light in Radians.
  48969. */
  48970. set: function (value) {
  48971. this._angle = value;
  48972. this._projectionTextureProjectionLightDirty = true;
  48973. this.forceProjectionMatrixCompute();
  48974. },
  48975. enumerable: true,
  48976. configurable: true
  48977. });
  48978. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48979. /**
  48980. * Allows scaling the angle of the light for shadow generation only.
  48981. */
  48982. get: function () {
  48983. return this._shadowAngleScale;
  48984. },
  48985. /**
  48986. * Allows scaling the angle of the light for shadow generation only.
  48987. */
  48988. set: function (value) {
  48989. this._shadowAngleScale = value;
  48990. this.forceProjectionMatrixCompute();
  48991. },
  48992. enumerable: true,
  48993. configurable: true
  48994. });
  48995. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48996. /**
  48997. * Allows reading the projecton texture
  48998. */
  48999. get: function () {
  49000. return this._projectionTextureMatrix;
  49001. },
  49002. enumerable: true,
  49003. configurable: true
  49004. });
  49005. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49006. /**
  49007. * Gets the near clip of the Spotlight for texture projection.
  49008. */
  49009. get: function () {
  49010. return this._projectionTextureLightNear;
  49011. },
  49012. /**
  49013. * Sets the near clip of the Spotlight for texture projection.
  49014. */
  49015. set: function (value) {
  49016. this._projectionTextureLightNear = value;
  49017. this._projectionTextureProjectionLightDirty = true;
  49018. },
  49019. enumerable: true,
  49020. configurable: true
  49021. });
  49022. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49023. /**
  49024. * Gets the far clip of the Spotlight for texture projection.
  49025. */
  49026. get: function () {
  49027. return this._projectionTextureLightFar;
  49028. },
  49029. /**
  49030. * Sets the far clip of the Spotlight for texture projection.
  49031. */
  49032. set: function (value) {
  49033. this._projectionTextureLightFar = value;
  49034. this._projectionTextureProjectionLightDirty = true;
  49035. },
  49036. enumerable: true,
  49037. configurable: true
  49038. });
  49039. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49040. /**
  49041. * Gets the Up vector of the Spotlight for texture projection.
  49042. */
  49043. get: function () {
  49044. return this._projectionTextureUpDirection;
  49045. },
  49046. /**
  49047. * Sets the Up vector of the Spotlight for texture projection.
  49048. */
  49049. set: function (value) {
  49050. this._projectionTextureUpDirection = value;
  49051. this._projectionTextureProjectionLightDirty = true;
  49052. },
  49053. enumerable: true,
  49054. configurable: true
  49055. });
  49056. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49057. /**
  49058. * Gets the projection texture of the light.
  49059. */
  49060. get: function () {
  49061. return this._projectionTexture;
  49062. },
  49063. /**
  49064. * Sets the projection texture of the light.
  49065. */
  49066. set: function (value) {
  49067. this._projectionTexture = value;
  49068. this._projectionTextureDirty = true;
  49069. },
  49070. enumerable: true,
  49071. configurable: true
  49072. });
  49073. /**
  49074. * Returns the string "SpotLight".
  49075. * @returns the class name
  49076. */
  49077. SpotLight.prototype.getClassName = function () {
  49078. return "SpotLight";
  49079. };
  49080. /**
  49081. * Returns the integer 2.
  49082. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49083. */
  49084. SpotLight.prototype.getTypeID = function () {
  49085. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49086. };
  49087. /**
  49088. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49089. */
  49090. SpotLight.prototype._setDirection = function (value) {
  49091. _super.prototype._setDirection.call(this, value);
  49092. this._projectionTextureViewLightDirty = true;
  49093. };
  49094. /**
  49095. * Overrides the position setter to recompute the projection texture view light Matrix.
  49096. */
  49097. SpotLight.prototype._setPosition = function (value) {
  49098. _super.prototype._setPosition.call(this, value);
  49099. this._projectionTextureViewLightDirty = true;
  49100. };
  49101. /**
  49102. * 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.
  49103. * Returns the SpotLight.
  49104. */
  49105. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49106. var activeCamera = this.getScene().activeCamera;
  49107. if (!activeCamera) {
  49108. return;
  49109. }
  49110. this._shadowAngleScale = this._shadowAngleScale || 1;
  49111. var angle = this._shadowAngleScale * this._angle;
  49112. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49113. };
  49114. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49115. this._projectionTextureViewLightDirty = false;
  49116. this._projectionTextureDirty = true;
  49117. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49118. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49119. };
  49120. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49121. this._projectionTextureProjectionLightDirty = false;
  49122. this._projectionTextureDirty = true;
  49123. var light_far = this.projectionTextureLightFar;
  49124. var light_near = this.projectionTextureLightNear;
  49125. var P = light_far / (light_far - light_near);
  49126. var Q = -P * light_near;
  49127. var S = 1.0 / Math.tan(this._angle / 2.0);
  49128. var A = 1.0;
  49129. 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);
  49130. };
  49131. /**
  49132. * Main function for light texture projection matrix computing.
  49133. */
  49134. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49135. this._projectionTextureDirty = false;
  49136. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49137. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49138. };
  49139. SpotLight.prototype._buildUniformLayout = function () {
  49140. this._uniformBuffer.addUniform("vLightData", 4);
  49141. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49142. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49143. this._uniformBuffer.addUniform("vLightDirection", 3);
  49144. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49145. this._uniformBuffer.addUniform("depthValues", 2);
  49146. this._uniformBuffer.create();
  49147. };
  49148. /**
  49149. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49150. * @param effect The effect to update
  49151. * @param lightIndex The index of the light in the effect to update
  49152. * @returns The spot light
  49153. */
  49154. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49155. var normalizeDirection;
  49156. if (this.computeTransformedInformation()) {
  49157. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49158. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49159. }
  49160. else {
  49161. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49162. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49163. }
  49164. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49165. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49166. if (this._projectionTextureViewLightDirty) {
  49167. this._computeProjectionTextureViewLightMatrix();
  49168. }
  49169. if (this._projectionTextureProjectionLightDirty) {
  49170. this._computeProjectionTextureProjectionLightMatrix();
  49171. }
  49172. if (this._projectionTextureDirty) {
  49173. this._computeProjectionTextureMatrix();
  49174. }
  49175. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49176. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49177. }
  49178. return this;
  49179. };
  49180. /**
  49181. * Disposes the light and the associated resources.
  49182. */
  49183. SpotLight.prototype.dispose = function () {
  49184. _super.prototype.dispose.call(this);
  49185. if (this._projectionTexture) {
  49186. this._projectionTexture.dispose();
  49187. }
  49188. };
  49189. __decorate([
  49190. BABYLON.serialize()
  49191. ], SpotLight.prototype, "angle", null);
  49192. __decorate([
  49193. BABYLON.serialize()
  49194. ], SpotLight.prototype, "shadowAngleScale", null);
  49195. __decorate([
  49196. BABYLON.serialize()
  49197. ], SpotLight.prototype, "exponent", void 0);
  49198. __decorate([
  49199. BABYLON.serialize()
  49200. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49201. __decorate([
  49202. BABYLON.serialize()
  49203. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49204. __decorate([
  49205. BABYLON.serialize()
  49206. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49207. __decorate([
  49208. BABYLON.serializeAsTexture("projectedLightTexture")
  49209. ], SpotLight.prototype, "_projectionTexture", void 0);
  49210. return SpotLight;
  49211. }(BABYLON.ShadowLight));
  49212. BABYLON.SpotLight = SpotLight;
  49213. })(BABYLON || (BABYLON = {}));
  49214. //# sourceMappingURL=babylon.spotLight.js.map
  49215. var BABYLON;
  49216. (function (BABYLON) {
  49217. /**
  49218. * Class used to override all child animations of a given target
  49219. */
  49220. var AnimationPropertiesOverride = /** @class */ (function () {
  49221. function AnimationPropertiesOverride() {
  49222. /**
  49223. * Gets or sets a value indicating if animation blending must be used
  49224. */
  49225. this.enableBlending = false;
  49226. /**
  49227. * Gets or sets the blending speed to use when enableBlending is true
  49228. */
  49229. this.blendingSpeed = 0.01;
  49230. /**
  49231. * Gets or sets the default loop mode to use
  49232. */
  49233. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49234. }
  49235. return AnimationPropertiesOverride;
  49236. }());
  49237. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49238. })(BABYLON || (BABYLON = {}));
  49239. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49240. var BABYLON;
  49241. (function (BABYLON) {
  49242. /**
  49243. * Represents the range of an animation
  49244. */
  49245. var AnimationRange = /** @class */ (function () {
  49246. /**
  49247. * Initializes the range of an animation
  49248. * @param name The name of the animation range
  49249. * @param from The starting frame of the animation
  49250. * @param to The ending frame of the animation
  49251. */
  49252. function AnimationRange(
  49253. /**The name of the animation range**/
  49254. name,
  49255. /**The starting frame of the animation */
  49256. from,
  49257. /**The ending frame of the animation*/
  49258. to) {
  49259. this.name = name;
  49260. this.from = from;
  49261. this.to = to;
  49262. }
  49263. /**
  49264. * Makes a copy of the animation range
  49265. * @returns A copy of the animation range
  49266. */
  49267. AnimationRange.prototype.clone = function () {
  49268. return new AnimationRange(this.name, this.from, this.to);
  49269. };
  49270. return AnimationRange;
  49271. }());
  49272. BABYLON.AnimationRange = AnimationRange;
  49273. /**
  49274. * Composed of a frame, and an action function
  49275. */
  49276. var AnimationEvent = /** @class */ (function () {
  49277. /**
  49278. * Initializes the animation event
  49279. * @param frame The frame for which the event is triggered
  49280. * @param action The event to perform when triggered
  49281. * @param onlyOnce Specifies if the event should be triggered only once
  49282. */
  49283. function AnimationEvent(
  49284. /** The frame for which the event is triggered **/
  49285. frame,
  49286. /** The event to perform when triggered **/
  49287. action,
  49288. /** Specifies if the event should be triggered only once**/
  49289. onlyOnce) {
  49290. this.frame = frame;
  49291. this.action = action;
  49292. this.onlyOnce = onlyOnce;
  49293. /**
  49294. * Specifies if the animation event is done
  49295. */
  49296. this.isDone = false;
  49297. }
  49298. /** @hidden */
  49299. AnimationEvent.prototype._clone = function () {
  49300. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49301. };
  49302. return AnimationEvent;
  49303. }());
  49304. BABYLON.AnimationEvent = AnimationEvent;
  49305. /**
  49306. * A cursor which tracks a point on a path
  49307. */
  49308. var PathCursor = /** @class */ (function () {
  49309. /**
  49310. * Initializes the path cursor
  49311. * @param path The path to track
  49312. */
  49313. function PathCursor(path) {
  49314. this.path = path;
  49315. /**
  49316. * Stores path cursor callbacks for when an onchange event is triggered
  49317. */
  49318. this._onchange = new Array();
  49319. /**
  49320. * The value of the path cursor
  49321. */
  49322. this.value = 0;
  49323. /**
  49324. * The animation array of the path cursor
  49325. */
  49326. this.animations = new Array();
  49327. }
  49328. /**
  49329. * Gets the cursor point on the path
  49330. * @returns A point on the path cursor at the cursor location
  49331. */
  49332. PathCursor.prototype.getPoint = function () {
  49333. var point = this.path.getPointAtLengthPosition(this.value);
  49334. return new BABYLON.Vector3(point.x, 0, point.y);
  49335. };
  49336. /**
  49337. * Moves the cursor ahead by the step amount
  49338. * @param step The amount to move the cursor forward
  49339. * @returns This path cursor
  49340. */
  49341. PathCursor.prototype.moveAhead = function (step) {
  49342. if (step === void 0) { step = 0.002; }
  49343. this.move(step);
  49344. return this;
  49345. };
  49346. /**
  49347. * Moves the cursor behind by the step amount
  49348. * @param step The amount to move the cursor back
  49349. * @returns This path cursor
  49350. */
  49351. PathCursor.prototype.moveBack = function (step) {
  49352. if (step === void 0) { step = 0.002; }
  49353. this.move(-step);
  49354. return this;
  49355. };
  49356. /**
  49357. * Moves the cursor by the step amount
  49358. * If the step amount is greater than one, an exception is thrown
  49359. * @param step The amount to move the cursor
  49360. * @returns This path cursor
  49361. */
  49362. PathCursor.prototype.move = function (step) {
  49363. if (Math.abs(step) > 1) {
  49364. throw "step size should be less than 1.";
  49365. }
  49366. this.value += step;
  49367. this.ensureLimits();
  49368. this.raiseOnChange();
  49369. return this;
  49370. };
  49371. /**
  49372. * Ensures that the value is limited between zero and one
  49373. * @returns This path cursor
  49374. */
  49375. PathCursor.prototype.ensureLimits = function () {
  49376. while (this.value > 1) {
  49377. this.value -= 1;
  49378. }
  49379. while (this.value < 0) {
  49380. this.value += 1;
  49381. }
  49382. return this;
  49383. };
  49384. /**
  49385. * Runs onchange callbacks on change (used by the animation engine)
  49386. * @returns This path cursor
  49387. */
  49388. PathCursor.prototype.raiseOnChange = function () {
  49389. var _this = this;
  49390. this._onchange.forEach(function (f) { return f(_this); });
  49391. return this;
  49392. };
  49393. /**
  49394. * Executes a function on change
  49395. * @param f A path cursor onchange callback
  49396. * @returns This path cursor
  49397. */
  49398. PathCursor.prototype.onchange = function (f) {
  49399. this._onchange.push(f);
  49400. return this;
  49401. };
  49402. return PathCursor;
  49403. }());
  49404. BABYLON.PathCursor = PathCursor;
  49405. /**
  49406. * Enum for the animation key frame interpolation type
  49407. */
  49408. var AnimationKeyInterpolation;
  49409. (function (AnimationKeyInterpolation) {
  49410. /**
  49411. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49412. */
  49413. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49414. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49415. /**
  49416. * Class used to store any kind of animation
  49417. */
  49418. var Animation = /** @class */ (function () {
  49419. /**
  49420. * Initializes the animation
  49421. * @param name Name of the animation
  49422. * @param targetProperty Property to animate
  49423. * @param framePerSecond The frames per second of the animation
  49424. * @param dataType The data type of the animation
  49425. * @param loopMode The loop mode of the animation
  49426. * @param enableBlendings Specifies if blending should be enabled
  49427. */
  49428. function Animation(
  49429. /**Name of the animation */
  49430. name,
  49431. /**Property to animate */
  49432. targetProperty,
  49433. /**The frames per second of the animation */
  49434. framePerSecond,
  49435. /**The data type of the animation */
  49436. dataType,
  49437. /**The loop mode of the animation */
  49438. loopMode,
  49439. /**Specifies if blending should be enabled */
  49440. enableBlending) {
  49441. this.name = name;
  49442. this.targetProperty = targetProperty;
  49443. this.framePerSecond = framePerSecond;
  49444. this.dataType = dataType;
  49445. this.loopMode = loopMode;
  49446. this.enableBlending = enableBlending;
  49447. /**
  49448. * @hidden Internal use only
  49449. */
  49450. this._runtimeAnimations = new Array();
  49451. /**
  49452. * The set of event that will be linked to this animation
  49453. */
  49454. this._events = new Array();
  49455. /**
  49456. * Stores the blending speed of the animation
  49457. */
  49458. this.blendingSpeed = 0.01;
  49459. /**
  49460. * Stores the animation ranges for the animation
  49461. */
  49462. this._ranges = {};
  49463. this.targetPropertyPath = targetProperty.split(".");
  49464. this.dataType = dataType;
  49465. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49466. }
  49467. /**
  49468. * @hidden Internal use
  49469. */
  49470. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49471. var dataType = undefined;
  49472. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49473. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49474. }
  49475. else if (from instanceof BABYLON.Quaternion) {
  49476. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49477. }
  49478. else if (from instanceof BABYLON.Vector3) {
  49479. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49480. }
  49481. else if (from instanceof BABYLON.Vector2) {
  49482. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49483. }
  49484. else if (from instanceof BABYLON.Color3) {
  49485. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49486. }
  49487. else if (from instanceof BABYLON.Size) {
  49488. dataType = Animation.ANIMATIONTYPE_SIZE;
  49489. }
  49490. if (dataType == undefined) {
  49491. return null;
  49492. }
  49493. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49494. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49495. animation.setKeys(keys);
  49496. if (easingFunction !== undefined) {
  49497. animation.setEasingFunction(easingFunction);
  49498. }
  49499. return animation;
  49500. };
  49501. /**
  49502. * Sets up an animation
  49503. * @param property The property to animate
  49504. * @param animationType The animation type to apply
  49505. * @param framePerSecond The frames per second of the animation
  49506. * @param easingFunction The easing function used in the animation
  49507. * @returns The created animation
  49508. */
  49509. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49510. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49511. animation.setEasingFunction(easingFunction);
  49512. return animation;
  49513. };
  49514. /**
  49515. * Create and start an animation on a node
  49516. * @param name defines the name of the global animation that will be run on all nodes
  49517. * @param node defines the root node where the animation will take place
  49518. * @param targetProperty defines property to animate
  49519. * @param framePerSecond defines the number of frame per second yo use
  49520. * @param totalFrame defines the number of frames in total
  49521. * @param from defines the initial value
  49522. * @param to defines the final value
  49523. * @param loopMode defines which loop mode you want to use (off by default)
  49524. * @param easingFunction defines the easing function to use (linear by default)
  49525. * @param onAnimationEnd defines the callback to call when animation end
  49526. * @returns the animatable created for this animation
  49527. */
  49528. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49529. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49530. if (!animation) {
  49531. return null;
  49532. }
  49533. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49534. };
  49535. /**
  49536. * Create and start an animation on a node and its descendants
  49537. * @param name defines the name of the global animation that will be run on all nodes
  49538. * @param node defines the root node where the animation will take place
  49539. * @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
  49540. * @param targetProperty defines property to animate
  49541. * @param framePerSecond defines the number of frame per second to use
  49542. * @param totalFrame defines the number of frames in total
  49543. * @param from defines the initial value
  49544. * @param to defines the final value
  49545. * @param loopMode defines which loop mode you want to use (off by default)
  49546. * @param easingFunction defines the easing function to use (linear by default)
  49547. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49548. * @returns the list of animatables created for all nodes
  49549. * @example https://www.babylonjs-playground.com/#MH0VLI
  49550. */
  49551. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49552. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49553. if (!animation) {
  49554. return null;
  49555. }
  49556. var scene = node.getScene();
  49557. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49558. };
  49559. /**
  49560. * Creates a new animation, merges it with the existing animations and starts it
  49561. * @param name Name of the animation
  49562. * @param node Node which contains the scene that begins the animations
  49563. * @param targetProperty Specifies which property to animate
  49564. * @param framePerSecond The frames per second of the animation
  49565. * @param totalFrame The total number of frames
  49566. * @param from The frame at the beginning of the animation
  49567. * @param to The frame at the end of the animation
  49568. * @param loopMode Specifies the loop mode of the animation
  49569. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49570. * @param onAnimationEnd Callback to run once the animation is complete
  49571. * @returns Nullable animation
  49572. */
  49573. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49574. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49575. if (!animation) {
  49576. return null;
  49577. }
  49578. node.animations.push(animation);
  49579. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49580. };
  49581. /**
  49582. * Transition property of an host to the target Value
  49583. * @param property The property to transition
  49584. * @param targetValue The target Value of the property
  49585. * @param host The object where the property to animate belongs
  49586. * @param scene Scene used to run the animation
  49587. * @param frameRate Framerate (in frame/s) to use
  49588. * @param transition The transition type we want to use
  49589. * @param duration The duration of the animation, in milliseconds
  49590. * @param onAnimationEnd Callback trigger at the end of the animation
  49591. * @returns Nullable animation
  49592. */
  49593. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49594. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49595. if (duration <= 0) {
  49596. host[property] = targetValue;
  49597. if (onAnimationEnd) {
  49598. onAnimationEnd();
  49599. }
  49600. return null;
  49601. }
  49602. var endFrame = frameRate * (duration / 1000);
  49603. transition.setKeys([{
  49604. frame: 0,
  49605. value: host[property].clone ? host[property].clone() : host[property]
  49606. },
  49607. {
  49608. frame: endFrame,
  49609. value: targetValue
  49610. }]);
  49611. if (!host.animations) {
  49612. host.animations = [];
  49613. }
  49614. host.animations.push(transition);
  49615. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49616. animation.onAnimationEnd = onAnimationEnd;
  49617. return animation;
  49618. };
  49619. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49620. /**
  49621. * Return the array of runtime animations currently using this animation
  49622. */
  49623. get: function () {
  49624. return this._runtimeAnimations;
  49625. },
  49626. enumerable: true,
  49627. configurable: true
  49628. });
  49629. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49630. /**
  49631. * Specifies if any of the runtime animations are currently running
  49632. */
  49633. get: function () {
  49634. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49635. var runtimeAnimation = _a[_i];
  49636. if (!runtimeAnimation.isStopped) {
  49637. return true;
  49638. }
  49639. }
  49640. return false;
  49641. },
  49642. enumerable: true,
  49643. configurable: true
  49644. });
  49645. // Methods
  49646. /**
  49647. * Converts the animation to a string
  49648. * @param fullDetails support for multiple levels of logging within scene loading
  49649. * @returns String form of the animation
  49650. */
  49651. Animation.prototype.toString = function (fullDetails) {
  49652. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49653. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49654. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49655. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49656. if (fullDetails) {
  49657. ret += ", Ranges: {";
  49658. var first = true;
  49659. for (var name in this._ranges) {
  49660. if (first) {
  49661. ret += ", ";
  49662. first = false;
  49663. }
  49664. ret += name;
  49665. }
  49666. ret += "}";
  49667. }
  49668. return ret;
  49669. };
  49670. /**
  49671. * Add an event to this animation
  49672. * @param event Event to add
  49673. */
  49674. Animation.prototype.addEvent = function (event) {
  49675. this._events.push(event);
  49676. };
  49677. /**
  49678. * Remove all events found at the given frame
  49679. * @param frame The frame to remove events from
  49680. */
  49681. Animation.prototype.removeEvents = function (frame) {
  49682. for (var index = 0; index < this._events.length; index++) {
  49683. if (this._events[index].frame === frame) {
  49684. this._events.splice(index, 1);
  49685. index--;
  49686. }
  49687. }
  49688. };
  49689. /**
  49690. * Retrieves all the events from the animation
  49691. * @returns Events from the animation
  49692. */
  49693. Animation.prototype.getEvents = function () {
  49694. return this._events;
  49695. };
  49696. /**
  49697. * Creates an animation range
  49698. * @param name Name of the animation range
  49699. * @param from Starting frame of the animation range
  49700. * @param to Ending frame of the animation
  49701. */
  49702. Animation.prototype.createRange = function (name, from, to) {
  49703. // check name not already in use; could happen for bones after serialized
  49704. if (!this._ranges[name]) {
  49705. this._ranges[name] = new AnimationRange(name, from, to);
  49706. }
  49707. };
  49708. /**
  49709. * Deletes an animation range by name
  49710. * @param name Name of the animation range to delete
  49711. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49712. */
  49713. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49714. if (deleteFrames === void 0) { deleteFrames = true; }
  49715. var range = this._ranges[name];
  49716. if (!range) {
  49717. return;
  49718. }
  49719. if (deleteFrames) {
  49720. var from = range.from;
  49721. var to = range.to;
  49722. // this loop MUST go high to low for multiple splices to work
  49723. for (var key = this._keys.length - 1; key >= 0; key--) {
  49724. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49725. this._keys.splice(key, 1);
  49726. }
  49727. }
  49728. }
  49729. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49730. };
  49731. /**
  49732. * Gets the animation range by name, or null if not defined
  49733. * @param name Name of the animation range
  49734. * @returns Nullable animation range
  49735. */
  49736. Animation.prototype.getRange = function (name) {
  49737. return this._ranges[name];
  49738. };
  49739. /**
  49740. * Gets the key frames from the animation
  49741. * @returns The key frames of the animation
  49742. */
  49743. Animation.prototype.getKeys = function () {
  49744. return this._keys;
  49745. };
  49746. /**
  49747. * Gets the highest frame rate of the animation
  49748. * @returns Highest frame rate of the animation
  49749. */
  49750. Animation.prototype.getHighestFrame = function () {
  49751. var ret = 0;
  49752. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49753. if (ret < this._keys[key].frame) {
  49754. ret = this._keys[key].frame;
  49755. }
  49756. }
  49757. return ret;
  49758. };
  49759. /**
  49760. * Gets the easing function of the animation
  49761. * @returns Easing function of the animation
  49762. */
  49763. Animation.prototype.getEasingFunction = function () {
  49764. return this._easingFunction;
  49765. };
  49766. /**
  49767. * Sets the easing function of the animation
  49768. * @param easingFunction A custom mathematical formula for animation
  49769. */
  49770. Animation.prototype.setEasingFunction = function (easingFunction) {
  49771. this._easingFunction = easingFunction;
  49772. };
  49773. /**
  49774. * Interpolates a scalar linearly
  49775. * @param startValue Start value of the animation curve
  49776. * @param endValue End value of the animation curve
  49777. * @param gradient Scalar amount to interpolate
  49778. * @returns Interpolated scalar value
  49779. */
  49780. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49781. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49782. };
  49783. /**
  49784. * Interpolates a scalar cubically
  49785. * @param startValue Start value of the animation curve
  49786. * @param outTangent End tangent of the animation
  49787. * @param endValue End value of the animation curve
  49788. * @param inTangent Start tangent of the animation curve
  49789. * @param gradient Scalar amount to interpolate
  49790. * @returns Interpolated scalar value
  49791. */
  49792. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49793. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49794. };
  49795. /**
  49796. * Interpolates a quaternion using a spherical linear interpolation
  49797. * @param startValue Start value of the animation curve
  49798. * @param endValue End value of the animation curve
  49799. * @param gradient Scalar amount to interpolate
  49800. * @returns Interpolated quaternion value
  49801. */
  49802. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49803. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49804. };
  49805. /**
  49806. * Interpolates a quaternion cubically
  49807. * @param startValue Start value of the animation curve
  49808. * @param outTangent End tangent of the animation curve
  49809. * @param endValue End value of the animation curve
  49810. * @param inTangent Start tangent of the animation curve
  49811. * @param gradient Scalar amount to interpolate
  49812. * @returns Interpolated quaternion value
  49813. */
  49814. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49815. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49816. };
  49817. /**
  49818. * Interpolates a Vector3 linearl
  49819. * @param startValue Start value of the animation curve
  49820. * @param endValue End value of the animation curve
  49821. * @param gradient Scalar amount to interpolate
  49822. * @returns Interpolated scalar value
  49823. */
  49824. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49825. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49826. };
  49827. /**
  49828. * Interpolates a Vector3 cubically
  49829. * @param startValue Start value of the animation curve
  49830. * @param outTangent End tangent of the animation
  49831. * @param endValue End value of the animation curve
  49832. * @param inTangent Start tangent of the animation curve
  49833. * @param gradient Scalar amount to interpolate
  49834. * @returns InterpolatedVector3 value
  49835. */
  49836. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49837. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49838. };
  49839. /**
  49840. * Interpolates a Vector2 linearly
  49841. * @param startValue Start value of the animation curve
  49842. * @param endValue End value of the animation curve
  49843. * @param gradient Scalar amount to interpolate
  49844. * @returns Interpolated Vector2 value
  49845. */
  49846. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49847. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49848. };
  49849. /**
  49850. * Interpolates a Vector2 cubically
  49851. * @param startValue Start value of the animation curve
  49852. * @param outTangent End tangent of the animation
  49853. * @param endValue End value of the animation curve
  49854. * @param inTangent Start tangent of the animation curve
  49855. * @param gradient Scalar amount to interpolate
  49856. * @returns Interpolated Vector2 value
  49857. */
  49858. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49859. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49860. };
  49861. /**
  49862. * Interpolates a size linearly
  49863. * @param startValue Start value of the animation curve
  49864. * @param endValue End value of the animation curve
  49865. * @param gradient Scalar amount to interpolate
  49866. * @returns Interpolated Size value
  49867. */
  49868. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49869. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49870. };
  49871. /**
  49872. * Interpolates a Color3 linearly
  49873. * @param startValue Start value of the animation curve
  49874. * @param endValue End value of the animation curve
  49875. * @param gradient Scalar amount to interpolate
  49876. * @returns Interpolated Color3 value
  49877. */
  49878. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49879. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49880. };
  49881. /**
  49882. * @hidden Internal use only
  49883. */
  49884. Animation.prototype._getKeyValue = function (value) {
  49885. if (typeof value === "function") {
  49886. return value();
  49887. }
  49888. return value;
  49889. };
  49890. /**
  49891. * @hidden Internal use only
  49892. */
  49893. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49894. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49895. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49896. }
  49897. var keys = this.getKeys();
  49898. // Try to get a hash to find the right key
  49899. 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));
  49900. if (keys[startKeyIndex].frame >= currentFrame) {
  49901. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49902. startKeyIndex--;
  49903. }
  49904. }
  49905. for (var key = startKeyIndex; key < keys.length; key++) {
  49906. var endKey = keys[key + 1];
  49907. if (endKey.frame >= currentFrame) {
  49908. var startKey = keys[key];
  49909. var startValue = this._getKeyValue(startKey.value);
  49910. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49911. return startValue;
  49912. }
  49913. var endValue = this._getKeyValue(endKey.value);
  49914. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49915. var frameDelta = endKey.frame - startKey.frame;
  49916. // gradient : percent of currentFrame between the frame inf and the frame sup
  49917. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49918. // check for easingFunction and correction of gradient
  49919. var easingFunction = this.getEasingFunction();
  49920. if (easingFunction != null) {
  49921. gradient = easingFunction.ease(gradient);
  49922. }
  49923. switch (this.dataType) {
  49924. // Float
  49925. case Animation.ANIMATIONTYPE_FLOAT:
  49926. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49927. switch (loopMode) {
  49928. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49929. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49930. return floatValue;
  49931. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49932. return offsetValue * repeatCount + floatValue;
  49933. }
  49934. break;
  49935. // Quaternion
  49936. case Animation.ANIMATIONTYPE_QUATERNION:
  49937. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49938. switch (loopMode) {
  49939. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49940. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49941. return quatValue;
  49942. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49943. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49944. }
  49945. return quatValue;
  49946. // Vector3
  49947. case Animation.ANIMATIONTYPE_VECTOR3:
  49948. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49949. switch (loopMode) {
  49950. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49951. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49952. return vec3Value;
  49953. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49954. return vec3Value.add(offsetValue.scale(repeatCount));
  49955. }
  49956. // Vector2
  49957. case Animation.ANIMATIONTYPE_VECTOR2:
  49958. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49959. switch (loopMode) {
  49960. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49961. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49962. return vec2Value;
  49963. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49964. return vec2Value.add(offsetValue.scale(repeatCount));
  49965. }
  49966. // Size
  49967. case Animation.ANIMATIONTYPE_SIZE:
  49968. switch (loopMode) {
  49969. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49970. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49971. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49972. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49973. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49974. }
  49975. // Color3
  49976. case Animation.ANIMATIONTYPE_COLOR3:
  49977. switch (loopMode) {
  49978. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49979. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49980. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49981. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49982. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49983. }
  49984. // Matrix
  49985. case Animation.ANIMATIONTYPE_MATRIX:
  49986. switch (loopMode) {
  49987. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49988. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49989. if (Animation.AllowMatricesInterpolation) {
  49990. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49991. }
  49992. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49993. return startValue;
  49994. }
  49995. default:
  49996. break;
  49997. }
  49998. break;
  49999. }
  50000. }
  50001. return this._getKeyValue(keys[keys.length - 1].value);
  50002. };
  50003. /**
  50004. * Defines the function to use to interpolate matrices
  50005. * @param startValue defines the start matrix
  50006. * @param endValue defines the end matrix
  50007. * @param gradient defines the gradient between both matrices
  50008. * @param result defines an optional target matrix where to store the interpolation
  50009. * @returns the interpolated matrix
  50010. */
  50011. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50012. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50013. if (result) {
  50014. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50015. return result;
  50016. }
  50017. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50018. }
  50019. if (result) {
  50020. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50021. return result;
  50022. }
  50023. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50024. };
  50025. /**
  50026. * Makes a copy of the animation
  50027. * @returns Cloned animation
  50028. */
  50029. Animation.prototype.clone = function () {
  50030. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50031. clone.enableBlending = this.enableBlending;
  50032. clone.blendingSpeed = this.blendingSpeed;
  50033. if (this._keys) {
  50034. clone.setKeys(this._keys);
  50035. }
  50036. if (this._ranges) {
  50037. clone._ranges = {};
  50038. for (var name in this._ranges) {
  50039. var range = this._ranges[name];
  50040. if (!range) {
  50041. continue;
  50042. }
  50043. clone._ranges[name] = range.clone();
  50044. }
  50045. }
  50046. return clone;
  50047. };
  50048. /**
  50049. * Sets the key frames of the animation
  50050. * @param values The animation key frames to set
  50051. */
  50052. Animation.prototype.setKeys = function (values) {
  50053. this._keys = values.slice(0);
  50054. };
  50055. /**
  50056. * Serializes the animation to an object
  50057. * @returns Serialized object
  50058. */
  50059. Animation.prototype.serialize = function () {
  50060. var serializationObject = {};
  50061. serializationObject.name = this.name;
  50062. serializationObject.property = this.targetProperty;
  50063. serializationObject.framePerSecond = this.framePerSecond;
  50064. serializationObject.dataType = this.dataType;
  50065. serializationObject.loopBehavior = this.loopMode;
  50066. serializationObject.enableBlending = this.enableBlending;
  50067. serializationObject.blendingSpeed = this.blendingSpeed;
  50068. var dataType = this.dataType;
  50069. serializationObject.keys = [];
  50070. var keys = this.getKeys();
  50071. for (var index = 0; index < keys.length; index++) {
  50072. var animationKey = keys[index];
  50073. var key = {};
  50074. key.frame = animationKey.frame;
  50075. switch (dataType) {
  50076. case Animation.ANIMATIONTYPE_FLOAT:
  50077. key.values = [animationKey.value];
  50078. break;
  50079. case Animation.ANIMATIONTYPE_QUATERNION:
  50080. case Animation.ANIMATIONTYPE_MATRIX:
  50081. case Animation.ANIMATIONTYPE_VECTOR3:
  50082. case Animation.ANIMATIONTYPE_COLOR3:
  50083. key.values = animationKey.value.asArray();
  50084. break;
  50085. }
  50086. serializationObject.keys.push(key);
  50087. }
  50088. serializationObject.ranges = [];
  50089. for (var name in this._ranges) {
  50090. var source = this._ranges[name];
  50091. if (!source) {
  50092. continue;
  50093. }
  50094. var range = {};
  50095. range.name = name;
  50096. range.from = source.from;
  50097. range.to = source.to;
  50098. serializationObject.ranges.push(range);
  50099. }
  50100. return serializationObject;
  50101. };
  50102. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50103. /**
  50104. * Get the float animation type
  50105. */
  50106. get: function () {
  50107. return Animation._ANIMATIONTYPE_FLOAT;
  50108. },
  50109. enumerable: true,
  50110. configurable: true
  50111. });
  50112. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50113. /**
  50114. * Get the Vector3 animation type
  50115. */
  50116. get: function () {
  50117. return Animation._ANIMATIONTYPE_VECTOR3;
  50118. },
  50119. enumerable: true,
  50120. configurable: true
  50121. });
  50122. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50123. /**
  50124. * Get the Vectpr2 animation type
  50125. */
  50126. get: function () {
  50127. return Animation._ANIMATIONTYPE_VECTOR2;
  50128. },
  50129. enumerable: true,
  50130. configurable: true
  50131. });
  50132. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50133. /**
  50134. * Get the Size animation type
  50135. */
  50136. get: function () {
  50137. return Animation._ANIMATIONTYPE_SIZE;
  50138. },
  50139. enumerable: true,
  50140. configurable: true
  50141. });
  50142. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50143. /**
  50144. * Get the Quaternion animation type
  50145. */
  50146. get: function () {
  50147. return Animation._ANIMATIONTYPE_QUATERNION;
  50148. },
  50149. enumerable: true,
  50150. configurable: true
  50151. });
  50152. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50153. /**
  50154. * Get the Matrix animation type
  50155. */
  50156. get: function () {
  50157. return Animation._ANIMATIONTYPE_MATRIX;
  50158. },
  50159. enumerable: true,
  50160. configurable: true
  50161. });
  50162. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50163. /**
  50164. * Get the Color3 animation type
  50165. */
  50166. get: function () {
  50167. return Animation._ANIMATIONTYPE_COLOR3;
  50168. },
  50169. enumerable: true,
  50170. configurable: true
  50171. });
  50172. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50173. /**
  50174. * Get the Relative Loop Mode
  50175. */
  50176. get: function () {
  50177. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50178. },
  50179. enumerable: true,
  50180. configurable: true
  50181. });
  50182. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50183. /**
  50184. * Get the Cycle Loop Mode
  50185. */
  50186. get: function () {
  50187. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50188. },
  50189. enumerable: true,
  50190. configurable: true
  50191. });
  50192. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50193. /**
  50194. * Get the Constant Loop Mode
  50195. */
  50196. get: function () {
  50197. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50198. },
  50199. enumerable: true,
  50200. configurable: true
  50201. });
  50202. /** @hidden */
  50203. Animation._UniversalLerp = function (left, right, amount) {
  50204. var constructor = left.constructor;
  50205. if (constructor.Lerp) { // Lerp supported
  50206. return constructor.Lerp(left, right, amount);
  50207. }
  50208. else if (constructor.Slerp) { // Slerp supported
  50209. return constructor.Slerp(left, right, amount);
  50210. }
  50211. else if (left.toFixed) { // Number
  50212. return left * (1.0 - amount) + amount * right;
  50213. }
  50214. else { // Blending not supported
  50215. return right;
  50216. }
  50217. };
  50218. /**
  50219. * Parses an animation object and creates an animation
  50220. * @param parsedAnimation Parsed animation object
  50221. * @returns Animation object
  50222. */
  50223. Animation.Parse = function (parsedAnimation) {
  50224. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50225. var dataType = parsedAnimation.dataType;
  50226. var keys = [];
  50227. var data;
  50228. var index;
  50229. if (parsedAnimation.enableBlending) {
  50230. animation.enableBlending = parsedAnimation.enableBlending;
  50231. }
  50232. if (parsedAnimation.blendingSpeed) {
  50233. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50234. }
  50235. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50236. var key = parsedAnimation.keys[index];
  50237. var inTangent;
  50238. var outTangent;
  50239. switch (dataType) {
  50240. case Animation.ANIMATIONTYPE_FLOAT:
  50241. data = key.values[0];
  50242. if (key.values.length >= 1) {
  50243. inTangent = key.values[1];
  50244. }
  50245. if (key.values.length >= 2) {
  50246. outTangent = key.values[2];
  50247. }
  50248. break;
  50249. case Animation.ANIMATIONTYPE_QUATERNION:
  50250. data = BABYLON.Quaternion.FromArray(key.values);
  50251. if (key.values.length >= 8) {
  50252. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50253. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50254. inTangent = _inTangent;
  50255. }
  50256. }
  50257. if (key.values.length >= 12) {
  50258. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50259. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50260. outTangent = _outTangent;
  50261. }
  50262. }
  50263. break;
  50264. case Animation.ANIMATIONTYPE_MATRIX:
  50265. data = BABYLON.Matrix.FromArray(key.values);
  50266. break;
  50267. case Animation.ANIMATIONTYPE_COLOR3:
  50268. data = BABYLON.Color3.FromArray(key.values);
  50269. break;
  50270. case Animation.ANIMATIONTYPE_VECTOR3:
  50271. default:
  50272. data = BABYLON.Vector3.FromArray(key.values);
  50273. break;
  50274. }
  50275. var keyData = {};
  50276. keyData.frame = key.frame;
  50277. keyData.value = data;
  50278. if (inTangent != undefined) {
  50279. keyData.inTangent = inTangent;
  50280. }
  50281. if (outTangent != undefined) {
  50282. keyData.outTangent = outTangent;
  50283. }
  50284. keys.push(keyData);
  50285. }
  50286. animation.setKeys(keys);
  50287. if (parsedAnimation.ranges) {
  50288. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50289. data = parsedAnimation.ranges[index];
  50290. animation.createRange(data.name, data.from, data.to);
  50291. }
  50292. }
  50293. return animation;
  50294. };
  50295. /**
  50296. * Appends the serialized animations from the source animations
  50297. * @param source Source containing the animations
  50298. * @param destination Target to store the animations
  50299. */
  50300. Animation.AppendSerializedAnimations = function (source, destination) {
  50301. if (source.animations) {
  50302. destination.animations = [];
  50303. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50304. var animation = source.animations[animationIndex];
  50305. destination.animations.push(animation.serialize());
  50306. }
  50307. }
  50308. };
  50309. /**
  50310. * Use matrix interpolation instead of using direct key value when animating matrices
  50311. */
  50312. Animation.AllowMatricesInterpolation = false;
  50313. /**
  50314. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50315. */
  50316. Animation.AllowMatrixDecomposeForInterpolation = true;
  50317. // Statics
  50318. /**
  50319. * Float animation type
  50320. */
  50321. Animation._ANIMATIONTYPE_FLOAT = 0;
  50322. /**
  50323. * Vector3 animation type
  50324. */
  50325. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50326. /**
  50327. * Quaternion animation type
  50328. */
  50329. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50330. /**
  50331. * Matrix animation type
  50332. */
  50333. Animation._ANIMATIONTYPE_MATRIX = 3;
  50334. /**
  50335. * Color3 animation type
  50336. */
  50337. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50338. /**
  50339. * Vector2 animation type
  50340. */
  50341. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50342. /**
  50343. * Size animation type
  50344. */
  50345. Animation._ANIMATIONTYPE_SIZE = 6;
  50346. /**
  50347. * Relative Loop Mode
  50348. */
  50349. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50350. /**
  50351. * Cycle Loop Mode
  50352. */
  50353. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50354. /**
  50355. * Constant Loop Mode
  50356. */
  50357. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50358. return Animation;
  50359. }());
  50360. BABYLON.Animation = Animation;
  50361. })(BABYLON || (BABYLON = {}));
  50362. //# sourceMappingURL=babylon.animation.js.map
  50363. var BABYLON;
  50364. (function (BABYLON) {
  50365. /**
  50366. * This class defines the direct association between an animation and a target
  50367. */
  50368. var TargetedAnimation = /** @class */ (function () {
  50369. function TargetedAnimation() {
  50370. }
  50371. return TargetedAnimation;
  50372. }());
  50373. BABYLON.TargetedAnimation = TargetedAnimation;
  50374. /**
  50375. * Use this class to create coordinated animations on multiple targets
  50376. */
  50377. var AnimationGroup = /** @class */ (function () {
  50378. function AnimationGroup(name, scene) {
  50379. if (scene === void 0) { scene = null; }
  50380. this.name = name;
  50381. this._targetedAnimations = new Array();
  50382. this._animatables = new Array();
  50383. this._from = Number.MAX_VALUE;
  50384. this._to = -Number.MAX_VALUE;
  50385. this._speedRatio = 1;
  50386. this.onAnimationEndObservable = new BABYLON.Observable();
  50387. /**
  50388. * This observable will notify when all animations have ended.
  50389. */
  50390. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50391. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50392. this._scene.animationGroups.push(this);
  50393. }
  50394. Object.defineProperty(AnimationGroup.prototype, "from", {
  50395. /**
  50396. * Gets the first frame
  50397. */
  50398. get: function () {
  50399. return this._from;
  50400. },
  50401. enumerable: true,
  50402. configurable: true
  50403. });
  50404. Object.defineProperty(AnimationGroup.prototype, "to", {
  50405. /**
  50406. * Gets the last frame
  50407. */
  50408. get: function () {
  50409. return this._to;
  50410. },
  50411. enumerable: true,
  50412. configurable: true
  50413. });
  50414. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50415. /**
  50416. * Define if the animations are started
  50417. */
  50418. get: function () {
  50419. return this._isStarted;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50425. /**
  50426. * Gets or sets the speed ratio to use for all animations
  50427. */
  50428. get: function () {
  50429. return this._speedRatio;
  50430. },
  50431. /**
  50432. * Gets or sets the speed ratio to use for all animations
  50433. */
  50434. set: function (value) {
  50435. if (this._speedRatio === value) {
  50436. return;
  50437. }
  50438. this._speedRatio = value;
  50439. for (var index = 0; index < this._animatables.length; index++) {
  50440. var animatable = this._animatables[index];
  50441. animatable.speedRatio = this._speedRatio;
  50442. }
  50443. },
  50444. enumerable: true,
  50445. configurable: true
  50446. });
  50447. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50448. /**
  50449. * Gets the targeted animations for this animation group
  50450. */
  50451. get: function () {
  50452. return this._targetedAnimations;
  50453. },
  50454. enumerable: true,
  50455. configurable: true
  50456. });
  50457. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50458. /**
  50459. * returning the list of animatables controlled by this animation group.
  50460. */
  50461. get: function () {
  50462. return this._animatables;
  50463. },
  50464. enumerable: true,
  50465. configurable: true
  50466. });
  50467. /**
  50468. * Add an animation (with its target) in the group
  50469. * @param animation defines the animation we want to add
  50470. * @param target defines the target of the animation
  50471. * @returns the {BABYLON.TargetedAnimation} object
  50472. */
  50473. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50474. var targetedAnimation = {
  50475. animation: animation,
  50476. target: target
  50477. };
  50478. var keys = animation.getKeys();
  50479. if (this._from > keys[0].frame) {
  50480. this._from = keys[0].frame;
  50481. }
  50482. if (this._to < keys[keys.length - 1].frame) {
  50483. this._to = keys[keys.length - 1].frame;
  50484. }
  50485. this._targetedAnimations.push(targetedAnimation);
  50486. return targetedAnimation;
  50487. };
  50488. /**
  50489. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50490. * It can add constant keys at begin or end
  50491. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50492. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50493. */
  50494. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50495. if (beginFrame === void 0) { beginFrame = null; }
  50496. if (endFrame === void 0) { endFrame = null; }
  50497. if (beginFrame == null)
  50498. beginFrame = this._from;
  50499. if (endFrame == null)
  50500. endFrame = this._to;
  50501. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50502. var targetedAnimation = this._targetedAnimations[index];
  50503. var keys = targetedAnimation.animation.getKeys();
  50504. var startKey = keys[0];
  50505. var endKey = keys[keys.length - 1];
  50506. if (startKey.frame > beginFrame) {
  50507. var newKey = {
  50508. frame: beginFrame,
  50509. value: startKey.value,
  50510. inTangent: startKey.inTangent,
  50511. outTangent: startKey.outTangent,
  50512. interpolation: startKey.interpolation
  50513. };
  50514. keys.splice(0, 0, newKey);
  50515. }
  50516. if (endKey.frame < endFrame) {
  50517. var newKey = {
  50518. frame: endFrame,
  50519. value: endKey.value,
  50520. inTangent: endKey.outTangent,
  50521. outTangent: endKey.outTangent,
  50522. interpolation: endKey.interpolation
  50523. };
  50524. keys.push(newKey);
  50525. }
  50526. }
  50527. this._from = beginFrame;
  50528. this._to = endFrame;
  50529. return this;
  50530. };
  50531. /**
  50532. * Start all animations on given targets
  50533. * @param loop defines if animations must loop
  50534. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50535. * @param from defines the from key (optional)
  50536. * @param to defines the to key (optional)
  50537. * @returns the current animation group
  50538. */
  50539. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50540. var _this = this;
  50541. if (loop === void 0) { loop = false; }
  50542. if (speedRatio === void 0) { speedRatio = 1; }
  50543. if (this._isStarted || this._targetedAnimations.length === 0) {
  50544. return this;
  50545. }
  50546. var _loop_1 = function (targetedAnimation) {
  50547. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50548. animatable.onAnimationEnd = function () {
  50549. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50550. _this._checkAnimationGroupEnded(animatable);
  50551. };
  50552. this_1._animatables.push(animatable);
  50553. };
  50554. var this_1 = this;
  50555. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50556. var targetedAnimation = _a[_i];
  50557. _loop_1(targetedAnimation);
  50558. }
  50559. this._speedRatio = speedRatio;
  50560. this._isStarted = true;
  50561. return this;
  50562. };
  50563. /**
  50564. * Pause all animations
  50565. */
  50566. AnimationGroup.prototype.pause = function () {
  50567. if (!this._isStarted) {
  50568. return this;
  50569. }
  50570. for (var index = 0; index < this._animatables.length; index++) {
  50571. var animatable = this._animatables[index];
  50572. animatable.pause();
  50573. }
  50574. return this;
  50575. };
  50576. /**
  50577. * Play all animations to initial state
  50578. * This function will start() the animations if they were not started or will restart() them if they were paused
  50579. * @param loop defines if animations must loop
  50580. */
  50581. AnimationGroup.prototype.play = function (loop) {
  50582. // only if all animatables are ready and exist
  50583. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50584. if (loop !== undefined) {
  50585. for (var index = 0; index < this._animatables.length; index++) {
  50586. var animatable = this._animatables[index];
  50587. animatable.loopAnimation = loop;
  50588. }
  50589. }
  50590. this.restart();
  50591. }
  50592. else {
  50593. this.stop();
  50594. this.start(loop, this._speedRatio);
  50595. }
  50596. return this;
  50597. };
  50598. /**
  50599. * Reset all animations to initial state
  50600. */
  50601. AnimationGroup.prototype.reset = function () {
  50602. if (!this._isStarted) {
  50603. return this;
  50604. }
  50605. for (var index = 0; index < this._animatables.length; index++) {
  50606. var animatable = this._animatables[index];
  50607. animatable.reset();
  50608. }
  50609. return this;
  50610. };
  50611. /**
  50612. * Restart animations from key 0
  50613. */
  50614. AnimationGroup.prototype.restart = function () {
  50615. if (!this._isStarted) {
  50616. return this;
  50617. }
  50618. for (var index = 0; index < this._animatables.length; index++) {
  50619. var animatable = this._animatables[index];
  50620. animatable.restart();
  50621. }
  50622. return this;
  50623. };
  50624. /**
  50625. * Stop all animations
  50626. */
  50627. AnimationGroup.prototype.stop = function () {
  50628. if (!this._isStarted) {
  50629. return this;
  50630. }
  50631. var list = this._animatables.slice();
  50632. for (var index = 0; index < list.length; index++) {
  50633. list[index].stop();
  50634. }
  50635. this._isStarted = false;
  50636. return this;
  50637. };
  50638. /**
  50639. * Set animation weight for all animatables
  50640. * @param weight defines the weight to use
  50641. * @return the animationGroup
  50642. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50643. */
  50644. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50645. for (var index = 0; index < this._animatables.length; index++) {
  50646. var animatable = this._animatables[index];
  50647. animatable.weight = weight;
  50648. }
  50649. return this;
  50650. };
  50651. /**
  50652. * Synchronize and normalize all animatables with a source animatable
  50653. * @param root defines the root animatable to synchronize with
  50654. * @return the animationGroup
  50655. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50656. */
  50657. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50658. for (var index = 0; index < this._animatables.length; index++) {
  50659. var animatable = this._animatables[index];
  50660. animatable.syncWith(root);
  50661. }
  50662. return this;
  50663. };
  50664. /**
  50665. * Goes to a specific frame in this animation group
  50666. * @param frame the frame number to go to
  50667. * @return the animationGroup
  50668. */
  50669. AnimationGroup.prototype.goToFrame = function (frame) {
  50670. if (!this._isStarted) {
  50671. return this;
  50672. }
  50673. for (var index = 0; index < this._animatables.length; index++) {
  50674. var animatable = this._animatables[index];
  50675. animatable.goToFrame(frame);
  50676. }
  50677. return this;
  50678. };
  50679. /**
  50680. * Dispose all associated resources
  50681. */
  50682. AnimationGroup.prototype.dispose = function () {
  50683. this._targetedAnimations = [];
  50684. this._animatables = [];
  50685. var index = this._scene.animationGroups.indexOf(this);
  50686. if (index > -1) {
  50687. this._scene.animationGroups.splice(index, 1);
  50688. }
  50689. };
  50690. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50691. // animatable should be taken out of the array
  50692. var idx = this._animatables.indexOf(animatable);
  50693. if (idx > -1) {
  50694. this._animatables.splice(idx, 1);
  50695. }
  50696. // all animatables were removed? animation group ended!
  50697. if (this._animatables.length === 0) {
  50698. this._isStarted = false;
  50699. this.onAnimationGroupEndObservable.notifyObservers(this);
  50700. }
  50701. };
  50702. return AnimationGroup;
  50703. }());
  50704. BABYLON.AnimationGroup = AnimationGroup;
  50705. })(BABYLON || (BABYLON = {}));
  50706. //# sourceMappingURL=babylon.animationGroup.js.map
  50707. var BABYLON;
  50708. (function (BABYLON) {
  50709. /**
  50710. * Defines a runtime animation
  50711. */
  50712. var RuntimeAnimation = /** @class */ (function () {
  50713. /**
  50714. * Create a new RuntimeAnimation object
  50715. * @param target defines the target of the animation
  50716. * @param animation defines the source animation object
  50717. * @param scene defines the hosting scene
  50718. * @param host defines the initiating Animatable
  50719. */
  50720. function RuntimeAnimation(target, animation, scene, host) {
  50721. var _this = this;
  50722. this._events = new Array();
  50723. /**
  50724. * The current frame of the runtime animation
  50725. */
  50726. this._currentFrame = 0;
  50727. /**
  50728. * The original value of the runtime animation
  50729. */
  50730. this._originalValue = new Array();
  50731. /**
  50732. * The offsets cache of the runtime animation
  50733. */
  50734. this._offsetsCache = {};
  50735. /**
  50736. * The high limits cache of the runtime animation
  50737. */
  50738. this._highLimitsCache = {};
  50739. /**
  50740. * Specifies if the runtime animation has been stopped
  50741. */
  50742. this._stopped = false;
  50743. /**
  50744. * The blending factor of the runtime animation
  50745. */
  50746. this._blendingFactor = 0;
  50747. /**
  50748. * The target path of the runtime animation
  50749. */
  50750. this._targetPath = "";
  50751. /**
  50752. * The weight of the runtime animation
  50753. */
  50754. this._weight = 1.0;
  50755. /**
  50756. * The ratio offset of the runtime animation
  50757. */
  50758. this._ratioOffset = 0;
  50759. /**
  50760. * The previous delay of the runtime animation
  50761. */
  50762. this._previousDelay = 0;
  50763. /**
  50764. * The previous ratio of the runtime animation
  50765. */
  50766. this._previousRatio = 0;
  50767. this._animation = animation;
  50768. this._target = target;
  50769. this._scene = scene;
  50770. this._host = host;
  50771. animation._runtimeAnimations.push(this);
  50772. // Cloning events locally
  50773. var events = animation.getEvents();
  50774. if (events && events.length > 0) {
  50775. events.forEach(function (e) {
  50776. _this._events.push(e._clone());
  50777. });
  50778. }
  50779. }
  50780. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50781. /**
  50782. * Gets the current frame of the runtime animation
  50783. */
  50784. get: function () {
  50785. return this._currentFrame;
  50786. },
  50787. enumerable: true,
  50788. configurable: true
  50789. });
  50790. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50791. /**
  50792. * Gets the weight of the runtime animation
  50793. */
  50794. get: function () {
  50795. return this._weight;
  50796. },
  50797. enumerable: true,
  50798. configurable: true
  50799. });
  50800. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50801. /**
  50802. * Gets the current value of the runtime animation
  50803. */
  50804. get: function () {
  50805. return this._currentValue;
  50806. },
  50807. enumerable: true,
  50808. configurable: true
  50809. });
  50810. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50811. /**
  50812. * Gets the target path of the runtime animation
  50813. */
  50814. get: function () {
  50815. return this._targetPath;
  50816. },
  50817. enumerable: true,
  50818. configurable: true
  50819. });
  50820. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50821. /**
  50822. * Gets the actual target of the runtime animation
  50823. */
  50824. get: function () {
  50825. return this._activeTarget;
  50826. },
  50827. enumerable: true,
  50828. configurable: true
  50829. });
  50830. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50831. /**
  50832. * Gets the animation from the runtime animation
  50833. */
  50834. get: function () {
  50835. return this._animation;
  50836. },
  50837. enumerable: true,
  50838. configurable: true
  50839. });
  50840. /**
  50841. * Resets the runtime animation to the beginning
  50842. * @param restoreOriginal defines whether to restore the target property to the original value
  50843. */
  50844. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50845. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50846. if (restoreOriginal) {
  50847. if (this._target instanceof Array) {
  50848. var index = 0;
  50849. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50850. var target = _a[_i];
  50851. if (this._originalValue[index] !== undefined) {
  50852. this._setValue(target, this._originalValue[index], -1);
  50853. }
  50854. index++;
  50855. }
  50856. }
  50857. else {
  50858. if (this._originalValue[0] !== undefined) {
  50859. this._setValue(this._target, this._originalValue[0], -1);
  50860. }
  50861. }
  50862. }
  50863. this._offsetsCache = {};
  50864. this._highLimitsCache = {};
  50865. this._currentFrame = 0;
  50866. this._blendingFactor = 0;
  50867. this._originalValue = new Array();
  50868. // Events
  50869. for (var index = 0; index < this._events.length; index++) {
  50870. this._events[index].isDone = false;
  50871. }
  50872. };
  50873. /**
  50874. * Specifies if the runtime animation is stopped
  50875. * @returns Boolean specifying if the runtime animation is stopped
  50876. */
  50877. RuntimeAnimation.prototype.isStopped = function () {
  50878. return this._stopped;
  50879. };
  50880. /**
  50881. * Disposes of the runtime animation
  50882. */
  50883. RuntimeAnimation.prototype.dispose = function () {
  50884. var index = this._animation.runtimeAnimations.indexOf(this);
  50885. if (index > -1) {
  50886. this._animation.runtimeAnimations.splice(index, 1);
  50887. }
  50888. };
  50889. /**
  50890. * Interpolates the animation from the current frame
  50891. * @param currentFrame The frame to interpolate the animation to
  50892. * @param repeatCount The number of times that the animation should loop
  50893. * @param loopMode The type of looping mode to use
  50894. * @param offsetValue Animation offset value
  50895. * @param highLimitValue The high limit value
  50896. * @returns The interpolated value
  50897. */
  50898. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50899. this._currentFrame = currentFrame;
  50900. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50901. this._workValue = BABYLON.Matrix.Zero();
  50902. }
  50903. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50904. };
  50905. /**
  50906. * Apply the interpolated value to the target
  50907. * @param currentValue defines the value computed by the animation
  50908. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50909. */
  50910. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50911. if (weight === void 0) { weight = 1.0; }
  50912. if (this._target instanceof Array) {
  50913. var index = 0;
  50914. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50915. var target = _a[_i];
  50916. this._setValue(target, currentValue, weight, index);
  50917. index++;
  50918. }
  50919. }
  50920. else {
  50921. this._setValue(this._target, currentValue, weight);
  50922. }
  50923. };
  50924. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50925. if (targetIndex === void 0) { targetIndex = 0; }
  50926. // Set value
  50927. var path;
  50928. var destination;
  50929. var targetPropertyPath = this._animation.targetPropertyPath;
  50930. if (targetPropertyPath.length > 1) {
  50931. var property = target[targetPropertyPath[0]];
  50932. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50933. property = property[targetPropertyPath[index]];
  50934. }
  50935. path = targetPropertyPath[targetPropertyPath.length - 1];
  50936. destination = property;
  50937. }
  50938. else {
  50939. path = targetPropertyPath[0];
  50940. destination = target;
  50941. }
  50942. this._targetPath = path;
  50943. this._activeTarget = destination;
  50944. this._weight = weight;
  50945. if (this._originalValue[targetIndex] === undefined) {
  50946. var originalValue = void 0;
  50947. if (destination.getRestPose && path === "_matrix") { // For bones
  50948. originalValue = destination.getRestPose();
  50949. }
  50950. else {
  50951. originalValue = destination[path];
  50952. }
  50953. if (originalValue && originalValue.clone) {
  50954. this._originalValue[targetIndex] = originalValue.clone();
  50955. }
  50956. else {
  50957. this._originalValue[targetIndex] = originalValue;
  50958. }
  50959. }
  50960. // Blending
  50961. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50962. if (enableBlending && this._blendingFactor <= 1.0) {
  50963. if (!this._originalBlendValue) {
  50964. var originalValue = destination[path];
  50965. if (originalValue.clone) {
  50966. this._originalBlendValue = originalValue.clone();
  50967. }
  50968. else {
  50969. this._originalBlendValue = originalValue;
  50970. }
  50971. }
  50972. if (this._originalBlendValue.m) { // Matrix
  50973. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50974. if (this._currentValue) {
  50975. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50976. }
  50977. else {
  50978. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50979. }
  50980. }
  50981. else {
  50982. if (this._currentValue) {
  50983. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50984. }
  50985. else {
  50986. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50987. }
  50988. }
  50989. }
  50990. else {
  50991. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50992. }
  50993. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50994. this._blendingFactor += blendingSpeed;
  50995. }
  50996. else {
  50997. this._currentValue = currentValue;
  50998. }
  50999. if (weight !== -1.0) {
  51000. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51001. }
  51002. else {
  51003. destination[path] = this._currentValue;
  51004. }
  51005. if (target.markAsDirty) {
  51006. target.markAsDirty(this._animation.targetProperty);
  51007. }
  51008. };
  51009. /**
  51010. * Gets the loop pmode of the runtime animation
  51011. * @returns Loop Mode
  51012. */
  51013. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51014. if (this._target && this._target.animationPropertiesOverride) {
  51015. return this._target.animationPropertiesOverride.loopMode;
  51016. }
  51017. return this._animation.loopMode;
  51018. };
  51019. /**
  51020. * Move the current animation to a given frame
  51021. * @param frame defines the frame to move to
  51022. */
  51023. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51024. var keys = this._animation.getKeys();
  51025. if (frame < keys[0].frame) {
  51026. frame = keys[0].frame;
  51027. }
  51028. else if (frame > keys[keys.length - 1].frame) {
  51029. frame = keys[keys.length - 1].frame;
  51030. }
  51031. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51032. this.setValue(currentValue, -1);
  51033. };
  51034. /**
  51035. * @hidden Internal use only
  51036. */
  51037. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51038. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51039. this._ratioOffset = this._previousRatio - newRatio;
  51040. };
  51041. /**
  51042. * Execute the current animation
  51043. * @param delay defines the delay to add to the current frame
  51044. * @param from defines the lower bound of the animation range
  51045. * @param to defines the upper bound of the animation range
  51046. * @param loop defines if the current animation must loop
  51047. * @param speedRatio defines the current speed ratio
  51048. * @param weight defines the weight of the animation (default is -1 so no weight)
  51049. * @returns a boolean indicating if the animation has ended
  51050. */
  51051. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51052. if (weight === void 0) { weight = -1.0; }
  51053. var targetPropertyPath = this._animation.targetPropertyPath;
  51054. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51055. this._stopped = true;
  51056. return false;
  51057. }
  51058. var keys = this._animation.getKeys();
  51059. // Return immediately if there is only one key frame.
  51060. if (keys.length === 1) {
  51061. this.setValue(keys[0].value, weight);
  51062. return !loop;
  51063. }
  51064. var returnValue = true;
  51065. // Adding a start key at frame 0 if missing
  51066. if (keys[0].frame !== 0) {
  51067. var newKey = { frame: 0, value: keys[0].value };
  51068. keys.splice(0, 0, newKey);
  51069. }
  51070. // Check limits
  51071. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51072. from = keys[0].frame;
  51073. }
  51074. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51075. to = keys[keys.length - 1].frame;
  51076. }
  51077. //to and from cannot be the same key
  51078. if (from === to) {
  51079. if (from > keys[0].frame) {
  51080. from--;
  51081. }
  51082. else if (to < keys[keys.length - 1].frame) {
  51083. to++;
  51084. }
  51085. }
  51086. // Compute ratio
  51087. var range = to - from;
  51088. var offsetValue;
  51089. // ratio represents the frame delta between from and to
  51090. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51091. var highLimitValue = 0;
  51092. this._previousDelay = delay;
  51093. this._previousRatio = ratio;
  51094. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51095. returnValue = false;
  51096. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51097. }
  51098. else {
  51099. // Get max value if required
  51100. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51101. var keyOffset = to.toString() + from.toString();
  51102. if (!this._offsetsCache[keyOffset]) {
  51103. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51104. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51105. switch (this._animation.dataType) {
  51106. // Float
  51107. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51108. this._offsetsCache[keyOffset] = toValue - fromValue;
  51109. break;
  51110. // Quaternion
  51111. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51112. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51113. break;
  51114. // Vector3
  51115. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51116. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51117. // Vector2
  51118. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51119. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51120. // Size
  51121. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51122. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51123. // Color3
  51124. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51125. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51126. default:
  51127. break;
  51128. }
  51129. this._highLimitsCache[keyOffset] = toValue;
  51130. }
  51131. highLimitValue = this._highLimitsCache[keyOffset];
  51132. offsetValue = this._offsetsCache[keyOffset];
  51133. }
  51134. }
  51135. if (offsetValue === undefined) {
  51136. switch (this._animation.dataType) {
  51137. // Float
  51138. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51139. offsetValue = 0;
  51140. break;
  51141. // Quaternion
  51142. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51143. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51144. break;
  51145. // Vector3
  51146. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51147. offsetValue = BABYLON.Vector3.Zero();
  51148. break;
  51149. // Vector2
  51150. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51151. offsetValue = BABYLON.Vector2.Zero();
  51152. break;
  51153. // Size
  51154. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51155. offsetValue = BABYLON.Size.Zero();
  51156. break;
  51157. // Color3
  51158. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51159. offsetValue = BABYLON.Color3.Black();
  51160. }
  51161. }
  51162. // Compute value
  51163. var repeatCount = (ratio / range) >> 0;
  51164. var currentFrame = returnValue ? from + ratio % range : to;
  51165. // Need to normalize?
  51166. if (this._host && this._host.syncRoot) {
  51167. var syncRoot = this._host.syncRoot;
  51168. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51169. currentFrame = from + (to - from) * hostNormalizedFrame;
  51170. }
  51171. // Reset events if looping
  51172. var events = this._events;
  51173. if (range > 0 && this.currentFrame > currentFrame ||
  51174. range < 0 && this.currentFrame < currentFrame) {
  51175. // Need to reset animation events
  51176. for (var index = 0; index < events.length; index++) {
  51177. if (!events[index].onlyOnce) {
  51178. // reset event, the animation is looping
  51179. events[index].isDone = false;
  51180. }
  51181. }
  51182. }
  51183. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51184. // Set value
  51185. this.setValue(currentValue, weight);
  51186. // Check events
  51187. for (var index = 0; index < events.length; index++) {
  51188. // Make sure current frame has passed event frame and that event frame is within the current range
  51189. // Also, handle both forward and reverse animations
  51190. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51191. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51192. var event = events[index];
  51193. if (!event.isDone) {
  51194. // If event should be done only once, remove it.
  51195. if (event.onlyOnce) {
  51196. events.splice(index, 1);
  51197. index--;
  51198. }
  51199. event.isDone = true;
  51200. event.action();
  51201. } // Don't do anything if the event has already be done.
  51202. }
  51203. }
  51204. if (!returnValue) {
  51205. this._stopped = true;
  51206. }
  51207. return returnValue;
  51208. };
  51209. return RuntimeAnimation;
  51210. }());
  51211. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51212. })(BABYLON || (BABYLON = {}));
  51213. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51214. var BABYLON;
  51215. (function (BABYLON) {
  51216. /**
  51217. * Class used to store an actual running animation
  51218. */
  51219. var Animatable = /** @class */ (function () {
  51220. /**
  51221. * Creates a new Animatable
  51222. * @param scene defines the hosting scene
  51223. * @param target defines the target object
  51224. * @param fromFrame defines the starting frame number (default is 0)
  51225. * @param toFrame defines the ending frame number (default is 100)
  51226. * @param loopAnimation defines if the animation must loop (default is false)
  51227. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51228. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51229. * @param animations defines a group of animation to add to the new Animatable
  51230. */
  51231. function Animatable(scene,
  51232. /** defines the target object */
  51233. target,
  51234. /** defines the starting frame number (default is 0) */
  51235. fromFrame,
  51236. /** defines the ending frame number (default is 100) */
  51237. toFrame,
  51238. /** defines if the animation must loop (default is false) */
  51239. loopAnimation, speedRatio,
  51240. /** defines a callback to call when animation ends if it is not looping */
  51241. onAnimationEnd, animations) {
  51242. if (fromFrame === void 0) { fromFrame = 0; }
  51243. if (toFrame === void 0) { toFrame = 100; }
  51244. if (loopAnimation === void 0) { loopAnimation = false; }
  51245. if (speedRatio === void 0) { speedRatio = 1.0; }
  51246. this.target = target;
  51247. this.fromFrame = fromFrame;
  51248. this.toFrame = toFrame;
  51249. this.loopAnimation = loopAnimation;
  51250. this.onAnimationEnd = onAnimationEnd;
  51251. this._localDelayOffset = null;
  51252. this._pausedDelay = null;
  51253. this._runtimeAnimations = new Array();
  51254. this._paused = false;
  51255. this._speedRatio = 1;
  51256. this._weight = -1.0;
  51257. /**
  51258. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51259. * This will only apply for non looping animation (default is true)
  51260. */
  51261. this.disposeOnEnd = true;
  51262. /**
  51263. * Gets a boolean indicating if the animation has started
  51264. */
  51265. this.animationStarted = false;
  51266. /**
  51267. * Observer raised when the animation ends
  51268. */
  51269. this.onAnimationEndObservable = new BABYLON.Observable();
  51270. this._scene = scene;
  51271. if (animations) {
  51272. this.appendAnimations(target, animations);
  51273. }
  51274. this._speedRatio = speedRatio;
  51275. scene._activeAnimatables.push(this);
  51276. }
  51277. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51278. /**
  51279. * Gets the root Animatable used to synchronize and normalize animations
  51280. */
  51281. get: function () {
  51282. return this._syncRoot;
  51283. },
  51284. enumerable: true,
  51285. configurable: true
  51286. });
  51287. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51288. /**
  51289. * Gets the current frame of the first RuntimeAnimation
  51290. * Used to synchronize Animatables
  51291. */
  51292. get: function () {
  51293. if (this._runtimeAnimations.length === 0) {
  51294. return 0;
  51295. }
  51296. return this._runtimeAnimations[0].currentFrame;
  51297. },
  51298. enumerable: true,
  51299. configurable: true
  51300. });
  51301. Object.defineProperty(Animatable.prototype, "weight", {
  51302. /**
  51303. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51304. */
  51305. get: function () {
  51306. return this._weight;
  51307. },
  51308. set: function (value) {
  51309. if (value === -1) { // -1 is ok and means no weight
  51310. this._weight = -1;
  51311. return;
  51312. }
  51313. // Else weight must be in [0, 1] range
  51314. this._weight = Math.min(Math.max(value, 0), 1.0);
  51315. },
  51316. enumerable: true,
  51317. configurable: true
  51318. });
  51319. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51320. /**
  51321. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51322. */
  51323. get: function () {
  51324. return this._speedRatio;
  51325. },
  51326. set: function (value) {
  51327. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51328. var animation = this._runtimeAnimations[index];
  51329. animation._prepareForSpeedRatioChange(value);
  51330. }
  51331. this._speedRatio = value;
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. // Methods
  51337. /**
  51338. * Synchronize and normalize current Animatable with a source Animatable
  51339. * This is useful when using animation weights and when animations are not of the same length
  51340. * @param root defines the root Animatable to synchronize with
  51341. * @returns the current Animatable
  51342. */
  51343. Animatable.prototype.syncWith = function (root) {
  51344. this._syncRoot = root;
  51345. if (root) {
  51346. // Make sure this animatable will animate after the root
  51347. var index = this._scene._activeAnimatables.indexOf(this);
  51348. if (index > -1) {
  51349. this._scene._activeAnimatables.splice(index, 1);
  51350. this._scene._activeAnimatables.push(this);
  51351. }
  51352. }
  51353. return this;
  51354. };
  51355. /**
  51356. * Gets the list of runtime animations
  51357. * @returns an array of RuntimeAnimation
  51358. */
  51359. Animatable.prototype.getAnimations = function () {
  51360. return this._runtimeAnimations;
  51361. };
  51362. /**
  51363. * Adds more animations to the current animatable
  51364. * @param target defines the target of the animations
  51365. * @param animations defines the new animations to add
  51366. */
  51367. Animatable.prototype.appendAnimations = function (target, animations) {
  51368. for (var index = 0; index < animations.length; index++) {
  51369. var animation = animations[index];
  51370. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51371. }
  51372. };
  51373. /**
  51374. * Gets the source animation for a specific property
  51375. * @param property defines the propertyu to look for
  51376. * @returns null or the source animation for the given property
  51377. */
  51378. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51379. var runtimeAnimations = this._runtimeAnimations;
  51380. for (var index = 0; index < runtimeAnimations.length; index++) {
  51381. if (runtimeAnimations[index].animation.targetProperty === property) {
  51382. return runtimeAnimations[index].animation;
  51383. }
  51384. }
  51385. return null;
  51386. };
  51387. /**
  51388. * Gets the runtime animation for a specific property
  51389. * @param property defines the propertyu to look for
  51390. * @returns null or the runtime animation for the given property
  51391. */
  51392. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51393. var runtimeAnimations = this._runtimeAnimations;
  51394. for (var index = 0; index < runtimeAnimations.length; index++) {
  51395. if (runtimeAnimations[index].animation.targetProperty === property) {
  51396. return runtimeAnimations[index];
  51397. }
  51398. }
  51399. return null;
  51400. };
  51401. /**
  51402. * Resets the animatable to its original state
  51403. */
  51404. Animatable.prototype.reset = function () {
  51405. var runtimeAnimations = this._runtimeAnimations;
  51406. for (var index = 0; index < runtimeAnimations.length; index++) {
  51407. runtimeAnimations[index].reset(true);
  51408. }
  51409. this._localDelayOffset = null;
  51410. this._pausedDelay = null;
  51411. };
  51412. /**
  51413. * Allows the animatable to blend with current running animations
  51414. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51415. * @param blendingSpeed defines the blending speed to use
  51416. */
  51417. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51418. var runtimeAnimations = this._runtimeAnimations;
  51419. for (var index = 0; index < runtimeAnimations.length; index++) {
  51420. runtimeAnimations[index].animation.enableBlending = true;
  51421. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51422. }
  51423. };
  51424. /**
  51425. * Disable animation blending
  51426. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51427. */
  51428. Animatable.prototype.disableBlending = function () {
  51429. var runtimeAnimations = this._runtimeAnimations;
  51430. for (var index = 0; index < runtimeAnimations.length; index++) {
  51431. runtimeAnimations[index].animation.enableBlending = false;
  51432. }
  51433. };
  51434. /**
  51435. * Jump directly to a given frame
  51436. * @param frame defines the frame to jump to
  51437. */
  51438. Animatable.prototype.goToFrame = function (frame) {
  51439. var runtimeAnimations = this._runtimeAnimations;
  51440. if (runtimeAnimations[0]) {
  51441. var fps = runtimeAnimations[0].animation.framePerSecond;
  51442. var currentFrame = runtimeAnimations[0].currentFrame;
  51443. var adjustTime = frame - currentFrame;
  51444. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51445. if (this._localDelayOffset === null) {
  51446. this._localDelayOffset = 0;
  51447. }
  51448. this._localDelayOffset -= delay;
  51449. }
  51450. for (var index = 0; index < runtimeAnimations.length; index++) {
  51451. runtimeAnimations[index].goToFrame(frame);
  51452. }
  51453. };
  51454. /**
  51455. * Pause the animation
  51456. */
  51457. Animatable.prototype.pause = function () {
  51458. if (this._paused) {
  51459. return;
  51460. }
  51461. this._paused = true;
  51462. };
  51463. /**
  51464. * Restart the animation
  51465. */
  51466. Animatable.prototype.restart = function () {
  51467. this._paused = false;
  51468. };
  51469. Animatable.prototype._raiseOnAnimationEnd = function () {
  51470. if (this.onAnimationEnd) {
  51471. this.onAnimationEnd();
  51472. }
  51473. this.onAnimationEndObservable.notifyObservers(this);
  51474. };
  51475. /**
  51476. * Stop and delete the current animation
  51477. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51478. */
  51479. Animatable.prototype.stop = function (animationName) {
  51480. if (animationName) {
  51481. var idx = this._scene._activeAnimatables.indexOf(this);
  51482. if (idx > -1) {
  51483. var runtimeAnimations = this._runtimeAnimations;
  51484. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51485. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51486. continue;
  51487. }
  51488. runtimeAnimations[index].dispose();
  51489. runtimeAnimations.splice(index, 1);
  51490. }
  51491. if (runtimeAnimations.length == 0) {
  51492. this._scene._activeAnimatables.splice(idx, 1);
  51493. this._raiseOnAnimationEnd();
  51494. }
  51495. }
  51496. }
  51497. else {
  51498. var index = this._scene._activeAnimatables.indexOf(this);
  51499. if (index > -1) {
  51500. this._scene._activeAnimatables.splice(index, 1);
  51501. var runtimeAnimations = this._runtimeAnimations;
  51502. for (var index = 0; index < runtimeAnimations.length; index++) {
  51503. runtimeAnimations[index].dispose();
  51504. }
  51505. this._raiseOnAnimationEnd();
  51506. }
  51507. }
  51508. };
  51509. /**
  51510. * Wait asynchronously for the animation to end
  51511. * @returns a promise which will be fullfilled when the animation ends
  51512. */
  51513. Animatable.prototype.waitAsync = function () {
  51514. var _this = this;
  51515. return new Promise(function (resolve, reject) {
  51516. _this.onAnimationEndObservable.add(function () {
  51517. resolve(_this);
  51518. }, undefined, undefined, _this, true);
  51519. });
  51520. };
  51521. /** @hidden */
  51522. Animatable.prototype._animate = function (delay) {
  51523. if (this._paused) {
  51524. this.animationStarted = false;
  51525. if (this._pausedDelay === null) {
  51526. this._pausedDelay = delay;
  51527. }
  51528. return true;
  51529. }
  51530. if (this._localDelayOffset === null) {
  51531. this._localDelayOffset = delay;
  51532. this._pausedDelay = null;
  51533. }
  51534. else if (this._pausedDelay !== null) {
  51535. this._localDelayOffset += delay - this._pausedDelay;
  51536. this._pausedDelay = null;
  51537. }
  51538. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51539. return true;
  51540. }
  51541. // Animating
  51542. var running = false;
  51543. var runtimeAnimations = this._runtimeAnimations;
  51544. var index;
  51545. for (index = 0; index < runtimeAnimations.length; index++) {
  51546. var animation = runtimeAnimations[index];
  51547. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51548. running = running || isRunning;
  51549. }
  51550. this.animationStarted = running;
  51551. if (!running) {
  51552. if (this.disposeOnEnd) {
  51553. // Remove from active animatables
  51554. index = this._scene._activeAnimatables.indexOf(this);
  51555. this._scene._activeAnimatables.splice(index, 1);
  51556. // Dispose all runtime animations
  51557. for (index = 0; index < runtimeAnimations.length; index++) {
  51558. runtimeAnimations[index].dispose();
  51559. }
  51560. }
  51561. this._raiseOnAnimationEnd();
  51562. if (this.disposeOnEnd) {
  51563. this.onAnimationEnd = null;
  51564. this.onAnimationEndObservable.clear();
  51565. }
  51566. }
  51567. return running;
  51568. };
  51569. return Animatable;
  51570. }());
  51571. BABYLON.Animatable = Animatable;
  51572. })(BABYLON || (BABYLON = {}));
  51573. //# sourceMappingURL=babylon.animatable.js.map
  51574. var BABYLON;
  51575. (function (BABYLON) {
  51576. var EasingFunction = /** @class */ (function () {
  51577. function EasingFunction() {
  51578. // Properties
  51579. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51580. }
  51581. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51582. get: function () {
  51583. return EasingFunction._EASINGMODE_EASEIN;
  51584. },
  51585. enumerable: true,
  51586. configurable: true
  51587. });
  51588. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51589. get: function () {
  51590. return EasingFunction._EASINGMODE_EASEOUT;
  51591. },
  51592. enumerable: true,
  51593. configurable: true
  51594. });
  51595. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51596. get: function () {
  51597. return EasingFunction._EASINGMODE_EASEINOUT;
  51598. },
  51599. enumerable: true,
  51600. configurable: true
  51601. });
  51602. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51603. var n = Math.min(Math.max(easingMode, 0), 2);
  51604. this._easingMode = n;
  51605. };
  51606. EasingFunction.prototype.getEasingMode = function () {
  51607. return this._easingMode;
  51608. };
  51609. EasingFunction.prototype.easeInCore = function (gradient) {
  51610. throw new Error('You must implement this method');
  51611. };
  51612. EasingFunction.prototype.ease = function (gradient) {
  51613. switch (this._easingMode) {
  51614. case EasingFunction.EASINGMODE_EASEIN:
  51615. return this.easeInCore(gradient);
  51616. case EasingFunction.EASINGMODE_EASEOUT:
  51617. return (1 - this.easeInCore(1 - gradient));
  51618. }
  51619. if (gradient >= 0.5) {
  51620. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51621. }
  51622. return (this.easeInCore(gradient * 2) * 0.5);
  51623. };
  51624. //Statics
  51625. EasingFunction._EASINGMODE_EASEIN = 0;
  51626. EasingFunction._EASINGMODE_EASEOUT = 1;
  51627. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51628. return EasingFunction;
  51629. }());
  51630. BABYLON.EasingFunction = EasingFunction;
  51631. var CircleEase = /** @class */ (function (_super) {
  51632. __extends(CircleEase, _super);
  51633. function CircleEase() {
  51634. return _super !== null && _super.apply(this, arguments) || this;
  51635. }
  51636. CircleEase.prototype.easeInCore = function (gradient) {
  51637. gradient = Math.max(0, Math.min(1, gradient));
  51638. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51639. };
  51640. return CircleEase;
  51641. }(EasingFunction));
  51642. BABYLON.CircleEase = CircleEase;
  51643. var BackEase = /** @class */ (function (_super) {
  51644. __extends(BackEase, _super);
  51645. function BackEase(amplitude) {
  51646. if (amplitude === void 0) { amplitude = 1; }
  51647. var _this = _super.call(this) || this;
  51648. _this.amplitude = amplitude;
  51649. return _this;
  51650. }
  51651. BackEase.prototype.easeInCore = function (gradient) {
  51652. var num = Math.max(0, this.amplitude);
  51653. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51654. };
  51655. return BackEase;
  51656. }(EasingFunction));
  51657. BABYLON.BackEase = BackEase;
  51658. var BounceEase = /** @class */ (function (_super) {
  51659. __extends(BounceEase, _super);
  51660. function BounceEase(bounces, bounciness) {
  51661. if (bounces === void 0) { bounces = 3; }
  51662. if (bounciness === void 0) { bounciness = 2; }
  51663. var _this = _super.call(this) || this;
  51664. _this.bounces = bounces;
  51665. _this.bounciness = bounciness;
  51666. return _this;
  51667. }
  51668. BounceEase.prototype.easeInCore = function (gradient) {
  51669. var y = Math.max(0.0, this.bounces);
  51670. var bounciness = this.bounciness;
  51671. if (bounciness <= 1.0) {
  51672. bounciness = 1.001;
  51673. }
  51674. var num9 = Math.pow(bounciness, y);
  51675. var num5 = 1.0 - bounciness;
  51676. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51677. var num15 = gradient * num4;
  51678. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51679. var num3 = Math.floor(num65);
  51680. var num13 = num3 + 1.0;
  51681. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51682. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51683. var num7 = (num8 + num12) * 0.5;
  51684. var num6 = gradient - num7;
  51685. var num2 = num7 - num8;
  51686. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51687. };
  51688. return BounceEase;
  51689. }(EasingFunction));
  51690. BABYLON.BounceEase = BounceEase;
  51691. var CubicEase = /** @class */ (function (_super) {
  51692. __extends(CubicEase, _super);
  51693. function CubicEase() {
  51694. return _super !== null && _super.apply(this, arguments) || this;
  51695. }
  51696. CubicEase.prototype.easeInCore = function (gradient) {
  51697. return (gradient * gradient * gradient);
  51698. };
  51699. return CubicEase;
  51700. }(EasingFunction));
  51701. BABYLON.CubicEase = CubicEase;
  51702. var ElasticEase = /** @class */ (function (_super) {
  51703. __extends(ElasticEase, _super);
  51704. function ElasticEase(oscillations, springiness) {
  51705. if (oscillations === void 0) { oscillations = 3; }
  51706. if (springiness === void 0) { springiness = 3; }
  51707. var _this = _super.call(this) || this;
  51708. _this.oscillations = oscillations;
  51709. _this.springiness = springiness;
  51710. return _this;
  51711. }
  51712. ElasticEase.prototype.easeInCore = function (gradient) {
  51713. var num2;
  51714. var num3 = Math.max(0.0, this.oscillations);
  51715. var num = Math.max(0.0, this.springiness);
  51716. if (num == 0) {
  51717. num2 = gradient;
  51718. }
  51719. else {
  51720. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51721. }
  51722. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51723. };
  51724. return ElasticEase;
  51725. }(EasingFunction));
  51726. BABYLON.ElasticEase = ElasticEase;
  51727. var ExponentialEase = /** @class */ (function (_super) {
  51728. __extends(ExponentialEase, _super);
  51729. function ExponentialEase(exponent) {
  51730. if (exponent === void 0) { exponent = 2; }
  51731. var _this = _super.call(this) || this;
  51732. _this.exponent = exponent;
  51733. return _this;
  51734. }
  51735. ExponentialEase.prototype.easeInCore = function (gradient) {
  51736. if (this.exponent <= 0) {
  51737. return gradient;
  51738. }
  51739. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51740. };
  51741. return ExponentialEase;
  51742. }(EasingFunction));
  51743. BABYLON.ExponentialEase = ExponentialEase;
  51744. var PowerEase = /** @class */ (function (_super) {
  51745. __extends(PowerEase, _super);
  51746. function PowerEase(power) {
  51747. if (power === void 0) { power = 2; }
  51748. var _this = _super.call(this) || this;
  51749. _this.power = power;
  51750. return _this;
  51751. }
  51752. PowerEase.prototype.easeInCore = function (gradient) {
  51753. var y = Math.max(0.0, this.power);
  51754. return Math.pow(gradient, y);
  51755. };
  51756. return PowerEase;
  51757. }(EasingFunction));
  51758. BABYLON.PowerEase = PowerEase;
  51759. var QuadraticEase = /** @class */ (function (_super) {
  51760. __extends(QuadraticEase, _super);
  51761. function QuadraticEase() {
  51762. return _super !== null && _super.apply(this, arguments) || this;
  51763. }
  51764. QuadraticEase.prototype.easeInCore = function (gradient) {
  51765. return (gradient * gradient);
  51766. };
  51767. return QuadraticEase;
  51768. }(EasingFunction));
  51769. BABYLON.QuadraticEase = QuadraticEase;
  51770. var QuarticEase = /** @class */ (function (_super) {
  51771. __extends(QuarticEase, _super);
  51772. function QuarticEase() {
  51773. return _super !== null && _super.apply(this, arguments) || this;
  51774. }
  51775. QuarticEase.prototype.easeInCore = function (gradient) {
  51776. return (gradient * gradient * gradient * gradient);
  51777. };
  51778. return QuarticEase;
  51779. }(EasingFunction));
  51780. BABYLON.QuarticEase = QuarticEase;
  51781. var QuinticEase = /** @class */ (function (_super) {
  51782. __extends(QuinticEase, _super);
  51783. function QuinticEase() {
  51784. return _super !== null && _super.apply(this, arguments) || this;
  51785. }
  51786. QuinticEase.prototype.easeInCore = function (gradient) {
  51787. return (gradient * gradient * gradient * gradient * gradient);
  51788. };
  51789. return QuinticEase;
  51790. }(EasingFunction));
  51791. BABYLON.QuinticEase = QuinticEase;
  51792. var SineEase = /** @class */ (function (_super) {
  51793. __extends(SineEase, _super);
  51794. function SineEase() {
  51795. return _super !== null && _super.apply(this, arguments) || this;
  51796. }
  51797. SineEase.prototype.easeInCore = function (gradient) {
  51798. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51799. };
  51800. return SineEase;
  51801. }(EasingFunction));
  51802. BABYLON.SineEase = SineEase;
  51803. var BezierCurveEase = /** @class */ (function (_super) {
  51804. __extends(BezierCurveEase, _super);
  51805. function BezierCurveEase(x1, y1, x2, y2) {
  51806. if (x1 === void 0) { x1 = 0; }
  51807. if (y1 === void 0) { y1 = 0; }
  51808. if (x2 === void 0) { x2 = 1; }
  51809. if (y2 === void 0) { y2 = 1; }
  51810. var _this = _super.call(this) || this;
  51811. _this.x1 = x1;
  51812. _this.y1 = y1;
  51813. _this.x2 = x2;
  51814. _this.y2 = y2;
  51815. return _this;
  51816. }
  51817. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51818. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51819. };
  51820. return BezierCurveEase;
  51821. }(EasingFunction));
  51822. BABYLON.BezierCurveEase = BezierCurveEase;
  51823. })(BABYLON || (BABYLON = {}));
  51824. //# sourceMappingURL=babylon.easing.js.map
  51825. var BABYLON;
  51826. (function (BABYLON) {
  51827. /**
  51828. * A Condition applied to an Action
  51829. */
  51830. var Condition = /** @class */ (function () {
  51831. /**
  51832. * Creates a new Condition
  51833. * @param actionManager the manager of the action the condition is applied to
  51834. */
  51835. function Condition(actionManager) {
  51836. this._actionManager = actionManager;
  51837. }
  51838. /**
  51839. * Check if the current condition is valid
  51840. * @returns a boolean
  51841. */
  51842. Condition.prototype.isValid = function () {
  51843. return true;
  51844. };
  51845. /**
  51846. * Internal only
  51847. * @hidden
  51848. */
  51849. Condition.prototype._getProperty = function (propertyPath) {
  51850. return this._actionManager._getProperty(propertyPath);
  51851. };
  51852. /**
  51853. * Internal only
  51854. * @hidden
  51855. */
  51856. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51857. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51858. };
  51859. /**
  51860. * Serialize placeholder for child classes
  51861. * @returns the serialized object
  51862. */
  51863. Condition.prototype.serialize = function () {
  51864. };
  51865. /**
  51866. * Internal only
  51867. * @hidden
  51868. */
  51869. Condition.prototype._serialize = function (serializedCondition) {
  51870. return {
  51871. type: 2,
  51872. children: [],
  51873. name: serializedCondition.name,
  51874. properties: serializedCondition.properties
  51875. };
  51876. };
  51877. return Condition;
  51878. }());
  51879. BABYLON.Condition = Condition;
  51880. /**
  51881. * Defines specific conditional operators as extensions of Condition
  51882. */
  51883. var ValueCondition = /** @class */ (function (_super) {
  51884. __extends(ValueCondition, _super);
  51885. /**
  51886. * Creates a new ValueCondition
  51887. * @param actionManager manager for the action the condition applies to
  51888. * @param target for the action
  51889. * @param propertyPath path to specify the property of the target the conditional operator uses
  51890. * @param value the value compared by the conditional operator against the current value of the property
  51891. * @param operator the conditional operator, default ValueCondition.IsEqual
  51892. */
  51893. function ValueCondition(actionManager, target,
  51894. /** path to specify the property of the target the conditional operator uses */
  51895. propertyPath,
  51896. /** the value compared by the conditional operator against the current value of the property */
  51897. value,
  51898. /** the conditional operator, default ValueCondition.IsEqual */
  51899. operator) {
  51900. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51901. var _this = _super.call(this, actionManager) || this;
  51902. _this.propertyPath = propertyPath;
  51903. _this.value = value;
  51904. _this.operator = operator;
  51905. _this._target = target;
  51906. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51907. _this._property = _this._getProperty(_this.propertyPath);
  51908. return _this;
  51909. }
  51910. Object.defineProperty(ValueCondition, "IsEqual", {
  51911. /**
  51912. * returns the number for IsEqual
  51913. */
  51914. get: function () {
  51915. return ValueCondition._IsEqual;
  51916. },
  51917. enumerable: true,
  51918. configurable: true
  51919. });
  51920. Object.defineProperty(ValueCondition, "IsDifferent", {
  51921. /**
  51922. * Returns the number for IsDifferent
  51923. */
  51924. get: function () {
  51925. return ValueCondition._IsDifferent;
  51926. },
  51927. enumerable: true,
  51928. configurable: true
  51929. });
  51930. Object.defineProperty(ValueCondition, "IsGreater", {
  51931. /**
  51932. * Returns the number for IsGreater
  51933. */
  51934. get: function () {
  51935. return ValueCondition._IsGreater;
  51936. },
  51937. enumerable: true,
  51938. configurable: true
  51939. });
  51940. Object.defineProperty(ValueCondition, "IsLesser", {
  51941. /**
  51942. * Returns the number for IsLesser
  51943. */
  51944. get: function () {
  51945. return ValueCondition._IsLesser;
  51946. },
  51947. enumerable: true,
  51948. configurable: true
  51949. });
  51950. /**
  51951. * Compares the given value with the property value for the specified conditional operator
  51952. * @returns the result of the comparison
  51953. */
  51954. ValueCondition.prototype.isValid = function () {
  51955. switch (this.operator) {
  51956. case ValueCondition.IsGreater:
  51957. return this._effectiveTarget[this._property] > this.value;
  51958. case ValueCondition.IsLesser:
  51959. return this._effectiveTarget[this._property] < this.value;
  51960. case ValueCondition.IsEqual:
  51961. case ValueCondition.IsDifferent:
  51962. var check;
  51963. if (this.value.equals) {
  51964. check = this.value.equals(this._effectiveTarget[this._property]);
  51965. }
  51966. else {
  51967. check = this.value === this._effectiveTarget[this._property];
  51968. }
  51969. return this.operator === ValueCondition.IsEqual ? check : !check;
  51970. }
  51971. return false;
  51972. };
  51973. /**
  51974. * Serialize the ValueCondition into a JSON compatible object
  51975. * @returns serialization object
  51976. */
  51977. ValueCondition.prototype.serialize = function () {
  51978. return this._serialize({
  51979. name: "ValueCondition",
  51980. properties: [
  51981. BABYLON.Action._GetTargetProperty(this._target),
  51982. { name: "propertyPath", value: this.propertyPath },
  51983. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51984. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51985. ]
  51986. });
  51987. };
  51988. /**
  51989. * Gets the name of the conditional operator for the ValueCondition
  51990. * @param operator the conditional operator
  51991. * @returns the name
  51992. */
  51993. ValueCondition.GetOperatorName = function (operator) {
  51994. switch (operator) {
  51995. case ValueCondition._IsEqual: return "IsEqual";
  51996. case ValueCondition._IsDifferent: return "IsDifferent";
  51997. case ValueCondition._IsGreater: return "IsGreater";
  51998. case ValueCondition._IsLesser: return "IsLesser";
  51999. default: return "";
  52000. }
  52001. };
  52002. /**
  52003. * Internal only
  52004. * @hidden
  52005. */
  52006. ValueCondition._IsEqual = 0;
  52007. /**
  52008. * Internal only
  52009. * @hidden
  52010. */
  52011. ValueCondition._IsDifferent = 1;
  52012. /**
  52013. * Internal only
  52014. * @hidden
  52015. */
  52016. ValueCondition._IsGreater = 2;
  52017. /**
  52018. * Internal only
  52019. * @hidden
  52020. */
  52021. ValueCondition._IsLesser = 3;
  52022. return ValueCondition;
  52023. }(Condition));
  52024. BABYLON.ValueCondition = ValueCondition;
  52025. /**
  52026. * Defines a predicate condition as an extension of Condition
  52027. */
  52028. var PredicateCondition = /** @class */ (function (_super) {
  52029. __extends(PredicateCondition, _super);
  52030. /**
  52031. * Creates a new PredicateCondition
  52032. * @param actionManager manager for the action the condition applies to
  52033. * @param predicate defines the predicate function used to validate the condition
  52034. */
  52035. function PredicateCondition(actionManager,
  52036. /** defines the predicate function used to validate the condition */
  52037. predicate) {
  52038. var _this = _super.call(this, actionManager) || this;
  52039. _this.predicate = predicate;
  52040. return _this;
  52041. }
  52042. /**
  52043. * @returns the validity of the predicate condition
  52044. */
  52045. PredicateCondition.prototype.isValid = function () {
  52046. return this.predicate();
  52047. };
  52048. return PredicateCondition;
  52049. }(Condition));
  52050. BABYLON.PredicateCondition = PredicateCondition;
  52051. /**
  52052. * Defines a state condition as an extension of Condition
  52053. */
  52054. var StateCondition = /** @class */ (function (_super) {
  52055. __extends(StateCondition, _super);
  52056. /**
  52057. * Creates a new StateCondition
  52058. * @param actionManager manager for the action the condition applies to
  52059. * @param target of the condition
  52060. * @param value to compare with target state
  52061. */
  52062. function StateCondition(actionManager, target, value) {
  52063. var _this = _super.call(this, actionManager) || this;
  52064. _this.value = value;
  52065. _this._target = target;
  52066. return _this;
  52067. }
  52068. /**
  52069. * @returns the validity of the state
  52070. */
  52071. StateCondition.prototype.isValid = function () {
  52072. return this._target.state === this.value;
  52073. };
  52074. /**
  52075. * Serialize the StateCondition into a JSON compatible object
  52076. * @returns serialization object
  52077. */
  52078. StateCondition.prototype.serialize = function () {
  52079. return this._serialize({
  52080. name: "StateCondition",
  52081. properties: [
  52082. BABYLON.Action._GetTargetProperty(this._target),
  52083. { name: "value", value: this.value }
  52084. ]
  52085. });
  52086. };
  52087. return StateCondition;
  52088. }(Condition));
  52089. BABYLON.StateCondition = StateCondition;
  52090. })(BABYLON || (BABYLON = {}));
  52091. //# sourceMappingURL=babylon.condition.js.map
  52092. var BABYLON;
  52093. (function (BABYLON) {
  52094. /**
  52095. * The action to be carried out following a trigger
  52096. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52097. */
  52098. var Action = /** @class */ (function () {
  52099. /**
  52100. * Creates a new Action
  52101. * @param triggerOptions the trigger, with or without parameters, for the action
  52102. * @param condition an optional determinant of action
  52103. */
  52104. function Action(
  52105. /** the trigger, with or without parameters, for the action */
  52106. triggerOptions, condition) {
  52107. this.triggerOptions = triggerOptions;
  52108. /**
  52109. * An event triggered prior to action being executed.
  52110. */
  52111. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52112. if (triggerOptions.parameter) {
  52113. this.trigger = triggerOptions.trigger;
  52114. this._triggerParameter = triggerOptions.parameter;
  52115. }
  52116. else {
  52117. this.trigger = triggerOptions;
  52118. }
  52119. this._nextActiveAction = this;
  52120. this._condition = condition;
  52121. }
  52122. /**
  52123. * Internal only
  52124. * @hidden
  52125. */
  52126. Action.prototype._prepare = function () {
  52127. };
  52128. /**
  52129. * Gets the trigger parameters
  52130. * @returns the trigger parameters
  52131. */
  52132. Action.prototype.getTriggerParameter = function () {
  52133. return this._triggerParameter;
  52134. };
  52135. /**
  52136. * Internal only - executes current action event
  52137. * @hidden
  52138. */
  52139. Action.prototype._executeCurrent = function (evt) {
  52140. if (this._nextActiveAction._condition) {
  52141. var condition = this._nextActiveAction._condition;
  52142. var currentRenderId = this._actionManager.getScene().getRenderId();
  52143. // We cache the current evaluation for the current frame
  52144. if (condition._evaluationId === currentRenderId) {
  52145. if (!condition._currentResult) {
  52146. return;
  52147. }
  52148. }
  52149. else {
  52150. condition._evaluationId = currentRenderId;
  52151. if (!condition.isValid()) {
  52152. condition._currentResult = false;
  52153. return;
  52154. }
  52155. condition._currentResult = true;
  52156. }
  52157. }
  52158. this.onBeforeExecuteObservable.notifyObservers(this);
  52159. this._nextActiveAction.execute(evt);
  52160. this.skipToNextActiveAction();
  52161. };
  52162. /**
  52163. * Execute placeholder for child classes
  52164. * @param evt optional action event
  52165. */
  52166. Action.prototype.execute = function (evt) {
  52167. };
  52168. /**
  52169. * Skips to next active action
  52170. */
  52171. Action.prototype.skipToNextActiveAction = function () {
  52172. if (this._nextActiveAction._child) {
  52173. if (!this._nextActiveAction._child._actionManager) {
  52174. this._nextActiveAction._child._actionManager = this._actionManager;
  52175. }
  52176. this._nextActiveAction = this._nextActiveAction._child;
  52177. }
  52178. else {
  52179. this._nextActiveAction = this;
  52180. }
  52181. };
  52182. /**
  52183. * Adds action to chain of actions, may be a DoNothingAction
  52184. * @param action defines the next action to execute
  52185. * @returns The action passed in
  52186. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52187. */
  52188. Action.prototype.then = function (action) {
  52189. this._child = action;
  52190. action._actionManager = this._actionManager;
  52191. action._prepare();
  52192. return action;
  52193. };
  52194. /**
  52195. * Internal only
  52196. * @hidden
  52197. */
  52198. Action.prototype._getProperty = function (propertyPath) {
  52199. return this._actionManager._getProperty(propertyPath);
  52200. };
  52201. /**
  52202. * Internal only
  52203. * @hidden
  52204. */
  52205. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52206. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52207. };
  52208. /**
  52209. * Serialize placeholder for child classes
  52210. * @param parent of child
  52211. * @returns the serialized object
  52212. */
  52213. Action.prototype.serialize = function (parent) {
  52214. };
  52215. /**
  52216. * Internal only called by serialize
  52217. * @hidden
  52218. */
  52219. Action.prototype._serialize = function (serializedAction, parent) {
  52220. var serializationObject = {
  52221. type: 1,
  52222. children: [],
  52223. name: serializedAction.name,
  52224. properties: serializedAction.properties || []
  52225. };
  52226. // Serialize child
  52227. if (this._child) {
  52228. this._child.serialize(serializationObject);
  52229. }
  52230. // Check if "this" has a condition
  52231. if (this._condition) {
  52232. var serializedCondition = this._condition.serialize();
  52233. serializedCondition.children.push(serializationObject);
  52234. if (parent) {
  52235. parent.children.push(serializedCondition);
  52236. }
  52237. return serializedCondition;
  52238. }
  52239. if (parent) {
  52240. parent.children.push(serializationObject);
  52241. }
  52242. return serializationObject;
  52243. };
  52244. /**
  52245. * Internal only
  52246. * @hidden
  52247. */
  52248. Action._SerializeValueAsString = function (value) {
  52249. if (typeof value === "number") {
  52250. return value.toString();
  52251. }
  52252. if (typeof value === "boolean") {
  52253. return value ? "true" : "false";
  52254. }
  52255. if (value instanceof BABYLON.Vector2) {
  52256. return value.x + ", " + value.y;
  52257. }
  52258. if (value instanceof BABYLON.Vector3) {
  52259. return value.x + ", " + value.y + ", " + value.z;
  52260. }
  52261. if (value instanceof BABYLON.Color3) {
  52262. return value.r + ", " + value.g + ", " + value.b;
  52263. }
  52264. if (value instanceof BABYLON.Color4) {
  52265. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52266. }
  52267. return value; // string
  52268. };
  52269. /**
  52270. * Internal only
  52271. * @hidden
  52272. */
  52273. Action._GetTargetProperty = function (target) {
  52274. return {
  52275. name: "target",
  52276. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52277. : target instanceof BABYLON.Light ? "LightProperties"
  52278. : target instanceof BABYLON.Camera ? "CameraProperties"
  52279. : "SceneProperties",
  52280. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52281. };
  52282. };
  52283. return Action;
  52284. }());
  52285. BABYLON.Action = Action;
  52286. })(BABYLON || (BABYLON = {}));
  52287. //# sourceMappingURL=babylon.action.js.map
  52288. var BABYLON;
  52289. (function (BABYLON) {
  52290. /**
  52291. * ActionEvent is the event being sent when an action is triggered.
  52292. */
  52293. var ActionEvent = /** @class */ (function () {
  52294. /**
  52295. * Creates a new ActionEvent
  52296. * @param source The mesh or sprite that triggered the action
  52297. * @param pointerX The X mouse cursor position at the time of the event
  52298. * @param pointerY The Y mouse cursor position at the time of the event
  52299. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52300. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52301. * @param additionalData additional data for the event
  52302. */
  52303. function ActionEvent(
  52304. /** The mesh or sprite that triggered the action */
  52305. source,
  52306. /** The X mouse cursor position at the time of the event */
  52307. pointerX,
  52308. /** The Y mouse cursor position at the time of the event */
  52309. pointerY,
  52310. /** The mesh that is currently pointed at (can be null) */
  52311. meshUnderPointer,
  52312. /** the original (browser) event that triggered the ActionEvent */
  52313. sourceEvent,
  52314. /** additional data for the event */
  52315. additionalData) {
  52316. this.source = source;
  52317. this.pointerX = pointerX;
  52318. this.pointerY = pointerY;
  52319. this.meshUnderPointer = meshUnderPointer;
  52320. this.sourceEvent = sourceEvent;
  52321. this.additionalData = additionalData;
  52322. }
  52323. /**
  52324. * Helper function to auto-create an ActionEvent from a source mesh.
  52325. * @param source The source mesh that triggered the event
  52326. * @param evt The original (browser) event
  52327. * @param additionalData additional data for the event
  52328. * @returns the new ActionEvent
  52329. */
  52330. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52331. var scene = source.getScene();
  52332. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52333. };
  52334. /**
  52335. * Helper function to auto-create an ActionEvent from a source sprite
  52336. * @param source The source sprite that triggered the event
  52337. * @param scene Scene associated with the sprite
  52338. * @param evt The original (browser) event
  52339. * @param additionalData additional data for the event
  52340. * @returns the new ActionEvent
  52341. */
  52342. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52343. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52344. };
  52345. /**
  52346. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52347. * @param scene the scene where the event occurred
  52348. * @param evt The original (browser) event
  52349. * @returns the new ActionEvent
  52350. */
  52351. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52352. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52353. };
  52354. /**
  52355. * Helper function to auto-create an ActionEvent from a primitive
  52356. * @param prim defines the target primitive
  52357. * @param pointerPos defines the pointer position
  52358. * @param evt The original (browser) event
  52359. * @param additionalData additional data for the event
  52360. * @returns the new ActionEvent
  52361. */
  52362. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52363. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52364. };
  52365. return ActionEvent;
  52366. }());
  52367. BABYLON.ActionEvent = ActionEvent;
  52368. /**
  52369. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52370. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52371. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52372. */
  52373. var ActionManager = /** @class */ (function () {
  52374. /**
  52375. * Creates a new action manager
  52376. * @param scene defines the hosting scene
  52377. */
  52378. function ActionManager(scene) {
  52379. // Members
  52380. /** Gets the list of actions */
  52381. this.actions = new Array();
  52382. /** Gets the cursor to use when hovering items */
  52383. this.hoverCursor = '';
  52384. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52385. scene.actionManagers.push(this);
  52386. }
  52387. Object.defineProperty(ActionManager, "NothingTrigger", {
  52388. /**
  52389. * Nothing
  52390. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52391. */
  52392. get: function () {
  52393. return ActionManager._NothingTrigger;
  52394. },
  52395. enumerable: true,
  52396. configurable: true
  52397. });
  52398. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52399. /**
  52400. * On pick
  52401. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52402. */
  52403. get: function () {
  52404. return ActionManager._OnPickTrigger;
  52405. },
  52406. enumerable: true,
  52407. configurable: true
  52408. });
  52409. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52410. /**
  52411. * On left pick
  52412. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52413. */
  52414. get: function () {
  52415. return ActionManager._OnLeftPickTrigger;
  52416. },
  52417. enumerable: true,
  52418. configurable: true
  52419. });
  52420. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52421. /**
  52422. * On right pick
  52423. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52424. */
  52425. get: function () {
  52426. return ActionManager._OnRightPickTrigger;
  52427. },
  52428. enumerable: true,
  52429. configurable: true
  52430. });
  52431. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52432. /**
  52433. * On center pick
  52434. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52435. */
  52436. get: function () {
  52437. return ActionManager._OnCenterPickTrigger;
  52438. },
  52439. enumerable: true,
  52440. configurable: true
  52441. });
  52442. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52443. /**
  52444. * On pick down
  52445. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52446. */
  52447. get: function () {
  52448. return ActionManager._OnPickDownTrigger;
  52449. },
  52450. enumerable: true,
  52451. configurable: true
  52452. });
  52453. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52454. /**
  52455. * On double pick
  52456. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52457. */
  52458. get: function () {
  52459. return ActionManager._OnDoublePickTrigger;
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52465. /**
  52466. * On pick up
  52467. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52468. */
  52469. get: function () {
  52470. return ActionManager._OnPickUpTrigger;
  52471. },
  52472. enumerable: true,
  52473. configurable: true
  52474. });
  52475. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52476. /**
  52477. * On pick out.
  52478. * This trigger will only be raised if you also declared a OnPickDown
  52479. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52480. */
  52481. get: function () {
  52482. return ActionManager._OnPickOutTrigger;
  52483. },
  52484. enumerable: true,
  52485. configurable: true
  52486. });
  52487. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52488. /**
  52489. * On long press
  52490. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52491. */
  52492. get: function () {
  52493. return ActionManager._OnLongPressTrigger;
  52494. },
  52495. enumerable: true,
  52496. configurable: true
  52497. });
  52498. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52499. /**
  52500. * On pointer over
  52501. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52502. */
  52503. get: function () {
  52504. return ActionManager._OnPointerOverTrigger;
  52505. },
  52506. enumerable: true,
  52507. configurable: true
  52508. });
  52509. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52510. /**
  52511. * On pointer out
  52512. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52513. */
  52514. get: function () {
  52515. return ActionManager._OnPointerOutTrigger;
  52516. },
  52517. enumerable: true,
  52518. configurable: true
  52519. });
  52520. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52521. /**
  52522. * On every frame
  52523. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52524. */
  52525. get: function () {
  52526. return ActionManager._OnEveryFrameTrigger;
  52527. },
  52528. enumerable: true,
  52529. configurable: true
  52530. });
  52531. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52532. /**
  52533. * On intersection enter
  52534. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52535. */
  52536. get: function () {
  52537. return ActionManager._OnIntersectionEnterTrigger;
  52538. },
  52539. enumerable: true,
  52540. configurable: true
  52541. });
  52542. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52543. /**
  52544. * On intersection exit
  52545. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52546. */
  52547. get: function () {
  52548. return ActionManager._OnIntersectionExitTrigger;
  52549. },
  52550. enumerable: true,
  52551. configurable: true
  52552. });
  52553. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52554. /**
  52555. * On key down
  52556. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52557. */
  52558. get: function () {
  52559. return ActionManager._OnKeyDownTrigger;
  52560. },
  52561. enumerable: true,
  52562. configurable: true
  52563. });
  52564. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52565. /**
  52566. * On key up
  52567. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52568. */
  52569. get: function () {
  52570. return ActionManager._OnKeyUpTrigger;
  52571. },
  52572. enumerable: true,
  52573. configurable: true
  52574. });
  52575. // Methods
  52576. /**
  52577. * Releases all associated resources
  52578. */
  52579. ActionManager.prototype.dispose = function () {
  52580. var index = this._scene.actionManagers.indexOf(this);
  52581. for (var i = 0; i < this.actions.length; i++) {
  52582. var action = this.actions[i];
  52583. ActionManager.Triggers[action.trigger]--;
  52584. if (ActionManager.Triggers[action.trigger] === 0) {
  52585. delete ActionManager.Triggers[action.trigger];
  52586. }
  52587. }
  52588. if (index > -1) {
  52589. this._scene.actionManagers.splice(index, 1);
  52590. }
  52591. };
  52592. /**
  52593. * Gets hosting scene
  52594. * @returns the hosting scene
  52595. */
  52596. ActionManager.prototype.getScene = function () {
  52597. return this._scene;
  52598. };
  52599. /**
  52600. * Does this action manager handles actions of any of the given triggers
  52601. * @param triggers defines the triggers to be tested
  52602. * @return a boolean indicating whether one (or more) of the triggers is handled
  52603. */
  52604. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52605. for (var index = 0; index < this.actions.length; index++) {
  52606. var action = this.actions[index];
  52607. if (triggers.indexOf(action.trigger) > -1) {
  52608. return true;
  52609. }
  52610. }
  52611. return false;
  52612. };
  52613. /**
  52614. * Does this action manager handles actions of a given trigger
  52615. * @param trigger defines the trigger to be tested
  52616. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52617. * @return whether the trigger is handled
  52618. */
  52619. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52620. for (var index = 0; index < this.actions.length; index++) {
  52621. var action = this.actions[index];
  52622. if (action.trigger === trigger) {
  52623. if (parameterPredicate) {
  52624. if (parameterPredicate(action.getTriggerParameter())) {
  52625. return true;
  52626. }
  52627. }
  52628. else {
  52629. return true;
  52630. }
  52631. }
  52632. }
  52633. return false;
  52634. };
  52635. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52636. /**
  52637. * Does this action manager has pointer triggers
  52638. */
  52639. get: function () {
  52640. for (var index = 0; index < this.actions.length; index++) {
  52641. var action = this.actions[index];
  52642. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52643. return true;
  52644. }
  52645. }
  52646. return false;
  52647. },
  52648. enumerable: true,
  52649. configurable: true
  52650. });
  52651. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52652. /**
  52653. * Does this action manager has pick triggers
  52654. */
  52655. get: function () {
  52656. for (var index = 0; index < this.actions.length; index++) {
  52657. var action = this.actions[index];
  52658. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52659. return true;
  52660. }
  52661. }
  52662. return false;
  52663. },
  52664. enumerable: true,
  52665. configurable: true
  52666. });
  52667. Object.defineProperty(ActionManager, "HasTriggers", {
  52668. /**
  52669. * Does exist one action manager with at least one trigger
  52670. **/
  52671. get: function () {
  52672. for (var t in ActionManager.Triggers) {
  52673. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52674. return true;
  52675. }
  52676. }
  52677. return false;
  52678. },
  52679. enumerable: true,
  52680. configurable: true
  52681. });
  52682. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52683. /**
  52684. * Does exist one action manager with at least one pick trigger
  52685. **/
  52686. get: function () {
  52687. for (var t in ActionManager.Triggers) {
  52688. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52689. var t_int = parseInt(t);
  52690. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52691. return true;
  52692. }
  52693. }
  52694. }
  52695. return false;
  52696. },
  52697. enumerable: true,
  52698. configurable: true
  52699. });
  52700. /**
  52701. * Does exist one action manager that handles actions of a given trigger
  52702. * @param trigger defines the trigger to be tested
  52703. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52704. **/
  52705. ActionManager.HasSpecificTrigger = function (trigger) {
  52706. for (var t in ActionManager.Triggers) {
  52707. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52708. var t_int = parseInt(t);
  52709. if (t_int === trigger) {
  52710. return true;
  52711. }
  52712. }
  52713. }
  52714. return false;
  52715. };
  52716. /**
  52717. * Registers an action to this action manager
  52718. * @param action defines the action to be registered
  52719. * @return the action amended (prepared) after registration
  52720. */
  52721. ActionManager.prototype.registerAction = function (action) {
  52722. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52723. if (this.getScene().actionManager !== this) {
  52724. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52725. return null;
  52726. }
  52727. }
  52728. this.actions.push(action);
  52729. if (ActionManager.Triggers[action.trigger]) {
  52730. ActionManager.Triggers[action.trigger]++;
  52731. }
  52732. else {
  52733. ActionManager.Triggers[action.trigger] = 1;
  52734. }
  52735. action._actionManager = this;
  52736. action._prepare();
  52737. return action;
  52738. };
  52739. /**
  52740. * Unregisters an action to this action manager
  52741. * @param action defines the action to be unregistered
  52742. * @return a boolean indicating whether the action has been unregistered
  52743. */
  52744. ActionManager.prototype.unregisterAction = function (action) {
  52745. var index = this.actions.indexOf(action);
  52746. if (index !== -1) {
  52747. this.actions.splice(index, 1);
  52748. ActionManager.Triggers[action.trigger] -= 1;
  52749. if (ActionManager.Triggers[action.trigger] === 0) {
  52750. delete ActionManager.Triggers[action.trigger];
  52751. }
  52752. delete action._actionManager;
  52753. return true;
  52754. }
  52755. return false;
  52756. };
  52757. /**
  52758. * Process a specific trigger
  52759. * @param trigger defines the trigger to process
  52760. * @param evt defines the event details to be processed
  52761. */
  52762. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52763. for (var index = 0; index < this.actions.length; index++) {
  52764. var action = this.actions[index];
  52765. if (action.trigger === trigger) {
  52766. if (evt) {
  52767. if (trigger === ActionManager.OnKeyUpTrigger
  52768. || trigger === ActionManager.OnKeyDownTrigger) {
  52769. var parameter = action.getTriggerParameter();
  52770. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52771. if (!parameter.toLowerCase) {
  52772. continue;
  52773. }
  52774. var lowerCase = parameter.toLowerCase();
  52775. if (lowerCase !== evt.sourceEvent.key) {
  52776. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52777. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52778. if (actualkey !== lowerCase) {
  52779. continue;
  52780. }
  52781. }
  52782. }
  52783. }
  52784. }
  52785. action._executeCurrent(evt);
  52786. }
  52787. }
  52788. };
  52789. /** @hidden */
  52790. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52791. var properties = propertyPath.split(".");
  52792. for (var index = 0; index < properties.length - 1; index++) {
  52793. target = target[properties[index]];
  52794. }
  52795. return target;
  52796. };
  52797. /** @hidden */
  52798. ActionManager.prototype._getProperty = function (propertyPath) {
  52799. var properties = propertyPath.split(".");
  52800. return properties[properties.length - 1];
  52801. };
  52802. /**
  52803. * Serialize this manager to a JSON object
  52804. * @param name defines the property name to store this manager
  52805. * @returns a JSON representation of this manager
  52806. */
  52807. ActionManager.prototype.serialize = function (name) {
  52808. var root = {
  52809. children: new Array(),
  52810. name: name,
  52811. type: 3,
  52812. properties: new Array() // Empty for root but required
  52813. };
  52814. for (var i = 0; i < this.actions.length; i++) {
  52815. var triggerObject = {
  52816. type: 0,
  52817. children: new Array(),
  52818. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52819. properties: new Array()
  52820. };
  52821. var triggerOptions = this.actions[i].triggerOptions;
  52822. if (triggerOptions && typeof triggerOptions !== "number") {
  52823. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52824. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52825. }
  52826. else {
  52827. var parameter = {};
  52828. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52829. if (triggerOptions.parameter.mesh) {
  52830. parameter._meshId = triggerOptions.parameter.mesh.id;
  52831. }
  52832. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52833. }
  52834. }
  52835. // Serialize child action, recursively
  52836. this.actions[i].serialize(triggerObject);
  52837. // Add serialized trigger
  52838. root.children.push(triggerObject);
  52839. }
  52840. return root;
  52841. };
  52842. /**
  52843. * Creates a new ActionManager from a JSON data
  52844. * @param parsedActions defines the JSON data to read from
  52845. * @param object defines the hosting mesh
  52846. * @param scene defines the hosting scene
  52847. */
  52848. ActionManager.Parse = function (parsedActions, object, scene) {
  52849. var actionManager = new ActionManager(scene);
  52850. if (object === null)
  52851. scene.actionManager = actionManager;
  52852. else
  52853. object.actionManager = actionManager;
  52854. // instanciate a new object
  52855. var instanciate = function (name, params) {
  52856. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52857. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52858. newInstance.constructor.apply(newInstance, params);
  52859. return newInstance;
  52860. };
  52861. var parseParameter = function (name, value, target, propertyPath) {
  52862. if (propertyPath === null) {
  52863. // String, boolean or float
  52864. var floatValue = parseFloat(value);
  52865. if (value === "true" || value === "false")
  52866. return value === "true";
  52867. else
  52868. return isNaN(floatValue) ? value : floatValue;
  52869. }
  52870. var effectiveTarget = propertyPath.split(".");
  52871. var values = value.split(",");
  52872. // Get effective Target
  52873. for (var i = 0; i < effectiveTarget.length; i++) {
  52874. target = target[effectiveTarget[i]];
  52875. }
  52876. // Return appropriate value with its type
  52877. if (typeof (target) === "boolean")
  52878. return values[0] === "true";
  52879. if (typeof (target) === "string")
  52880. return values[0];
  52881. // Parameters with multiple values such as Vector3 etc.
  52882. var split = new Array();
  52883. for (var i = 0; i < values.length; i++)
  52884. split.push(parseFloat(values[i]));
  52885. if (target instanceof BABYLON.Vector3)
  52886. return BABYLON.Vector3.FromArray(split);
  52887. if (target instanceof BABYLON.Vector4)
  52888. return BABYLON.Vector4.FromArray(split);
  52889. if (target instanceof BABYLON.Color3)
  52890. return BABYLON.Color3.FromArray(split);
  52891. if (target instanceof BABYLON.Color4)
  52892. return BABYLON.Color4.FromArray(split);
  52893. return parseFloat(values[0]);
  52894. };
  52895. // traverse graph per trigger
  52896. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52897. if (combineArray === void 0) { combineArray = null; }
  52898. if (parsedAction.detached)
  52899. return;
  52900. var parameters = new Array();
  52901. var target = null;
  52902. var propertyPath = null;
  52903. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52904. // Parameters
  52905. if (parsedAction.type === 2)
  52906. parameters.push(actionManager);
  52907. else
  52908. parameters.push(trigger);
  52909. if (combine) {
  52910. var actions = new Array();
  52911. for (var j = 0; j < parsedAction.combine.length; j++) {
  52912. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52913. }
  52914. parameters.push(actions);
  52915. }
  52916. else {
  52917. for (var i = 0; i < parsedAction.properties.length; i++) {
  52918. var value = parsedAction.properties[i].value;
  52919. var name = parsedAction.properties[i].name;
  52920. var targetType = parsedAction.properties[i].targetType;
  52921. if (name === "target")
  52922. if (targetType !== null && targetType === "SceneProperties")
  52923. value = target = scene;
  52924. else
  52925. value = target = scene.getNodeByName(value);
  52926. else if (name === "parent")
  52927. value = scene.getNodeByName(value);
  52928. else if (name === "sound")
  52929. value = scene.getSoundByName(value);
  52930. else if (name !== "propertyPath") {
  52931. if (parsedAction.type === 2 && name === "operator")
  52932. value = BABYLON.ValueCondition[value];
  52933. else
  52934. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52935. }
  52936. else {
  52937. propertyPath = value;
  52938. }
  52939. parameters.push(value);
  52940. }
  52941. }
  52942. if (combineArray === null) {
  52943. parameters.push(condition);
  52944. }
  52945. else {
  52946. parameters.push(null);
  52947. }
  52948. // If interpolate value action
  52949. if (parsedAction.name === "InterpolateValueAction") {
  52950. var param = parameters[parameters.length - 2];
  52951. parameters[parameters.length - 1] = param;
  52952. parameters[parameters.length - 2] = condition;
  52953. }
  52954. // Action or condition(s) and not CombineAction
  52955. var newAction = instanciate(parsedAction.name, parameters);
  52956. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52957. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52958. if (action)
  52959. action.then(nothing);
  52960. else
  52961. actionManager.registerAction(nothing);
  52962. action = nothing;
  52963. }
  52964. if (combineArray === null) {
  52965. if (newAction instanceof BABYLON.Condition) {
  52966. condition = newAction;
  52967. newAction = action;
  52968. }
  52969. else {
  52970. condition = null;
  52971. if (action)
  52972. action.then(newAction);
  52973. else
  52974. actionManager.registerAction(newAction);
  52975. }
  52976. }
  52977. else {
  52978. combineArray.push(newAction);
  52979. }
  52980. for (var i = 0; i < parsedAction.children.length; i++)
  52981. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52982. };
  52983. // triggers
  52984. for (var i = 0; i < parsedActions.children.length; i++) {
  52985. var triggerParams;
  52986. var trigger = parsedActions.children[i];
  52987. if (trigger.properties.length > 0) {
  52988. var param = trigger.properties[0].value;
  52989. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52990. if (value._meshId) {
  52991. value.mesh = scene.getMeshByID(value._meshId);
  52992. }
  52993. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52994. }
  52995. else
  52996. triggerParams = ActionManager[trigger.name];
  52997. for (var j = 0; j < trigger.children.length; j++) {
  52998. if (!trigger.detached)
  52999. traverse(trigger.children[j], triggerParams, null, null);
  53000. }
  53001. }
  53002. };
  53003. /**
  53004. * Get a trigger name by index
  53005. * @param trigger defines the trigger index
  53006. * @returns a trigger name
  53007. */
  53008. ActionManager.GetTriggerName = function (trigger) {
  53009. switch (trigger) {
  53010. case 0: return "NothingTrigger";
  53011. case 1: return "OnPickTrigger";
  53012. case 2: return "OnLeftPickTrigger";
  53013. case 3: return "OnRightPickTrigger";
  53014. case 4: return "OnCenterPickTrigger";
  53015. case 5: return "OnPickDownTrigger";
  53016. case 6: return "OnPickUpTrigger";
  53017. case 7: return "OnLongPressTrigger";
  53018. case 8: return "OnPointerOverTrigger";
  53019. case 9: return "OnPointerOutTrigger";
  53020. case 10: return "OnEveryFrameTrigger";
  53021. case 11: return "OnIntersectionEnterTrigger";
  53022. case 12: return "OnIntersectionExitTrigger";
  53023. case 13: return "OnKeyDownTrigger";
  53024. case 14: return "OnKeyUpTrigger";
  53025. case 15: return "OnPickOutTrigger";
  53026. default: return "";
  53027. }
  53028. };
  53029. // Statics
  53030. ActionManager._NothingTrigger = 0;
  53031. ActionManager._OnPickTrigger = 1;
  53032. ActionManager._OnLeftPickTrigger = 2;
  53033. ActionManager._OnRightPickTrigger = 3;
  53034. ActionManager._OnCenterPickTrigger = 4;
  53035. ActionManager._OnPickDownTrigger = 5;
  53036. ActionManager._OnDoublePickTrigger = 6;
  53037. ActionManager._OnPickUpTrigger = 7;
  53038. ActionManager._OnLongPressTrigger = 8;
  53039. ActionManager._OnPointerOverTrigger = 9;
  53040. ActionManager._OnPointerOutTrigger = 10;
  53041. ActionManager._OnEveryFrameTrigger = 11;
  53042. ActionManager._OnIntersectionEnterTrigger = 12;
  53043. ActionManager._OnIntersectionExitTrigger = 13;
  53044. ActionManager._OnKeyDownTrigger = 14;
  53045. ActionManager._OnKeyUpTrigger = 15;
  53046. ActionManager._OnPickOutTrigger = 16;
  53047. /** Gets the list of active triggers */
  53048. ActionManager.Triggers = {};
  53049. return ActionManager;
  53050. }());
  53051. BABYLON.ActionManager = ActionManager;
  53052. })(BABYLON || (BABYLON = {}));
  53053. //# sourceMappingURL=babylon.actionManager.js.map
  53054. var BABYLON;
  53055. (function (BABYLON) {
  53056. var InterpolateValueAction = /** @class */ (function (_super) {
  53057. __extends(InterpolateValueAction, _super);
  53058. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53059. if (duration === void 0) { duration = 1000; }
  53060. var _this = _super.call(this, triggerOptions, condition) || this;
  53061. _this.propertyPath = propertyPath;
  53062. _this.value = value;
  53063. _this.duration = duration;
  53064. _this.stopOtherAnimations = stopOtherAnimations;
  53065. _this.onInterpolationDone = onInterpolationDone;
  53066. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53067. _this._target = _this._effectiveTarget = target;
  53068. return _this;
  53069. }
  53070. InterpolateValueAction.prototype._prepare = function () {
  53071. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53072. this._property = this._getProperty(this.propertyPath);
  53073. };
  53074. InterpolateValueAction.prototype.execute = function () {
  53075. var _this = this;
  53076. var scene = this._actionManager.getScene();
  53077. var keys = [
  53078. {
  53079. frame: 0,
  53080. value: this._effectiveTarget[this._property]
  53081. }, {
  53082. frame: 100,
  53083. value: this.value
  53084. }
  53085. ];
  53086. var dataType;
  53087. if (typeof this.value === "number") {
  53088. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53089. }
  53090. else if (this.value instanceof BABYLON.Color3) {
  53091. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53092. }
  53093. else if (this.value instanceof BABYLON.Vector3) {
  53094. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53095. }
  53096. else if (this.value instanceof BABYLON.Matrix) {
  53097. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53098. }
  53099. else if (this.value instanceof BABYLON.Quaternion) {
  53100. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53101. }
  53102. else {
  53103. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53104. return;
  53105. }
  53106. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53107. animation.setKeys(keys);
  53108. if (this.stopOtherAnimations) {
  53109. scene.stopAnimation(this._effectiveTarget);
  53110. }
  53111. var wrapper = function () {
  53112. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53113. if (_this.onInterpolationDone) {
  53114. _this.onInterpolationDone();
  53115. }
  53116. };
  53117. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53118. };
  53119. InterpolateValueAction.prototype.serialize = function (parent) {
  53120. return _super.prototype._serialize.call(this, {
  53121. name: "InterpolateValueAction",
  53122. properties: [
  53123. BABYLON.Action._GetTargetProperty(this._target),
  53124. { name: "propertyPath", value: this.propertyPath },
  53125. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53126. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53127. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53128. ]
  53129. }, parent);
  53130. };
  53131. return InterpolateValueAction;
  53132. }(BABYLON.Action));
  53133. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53134. })(BABYLON || (BABYLON = {}));
  53135. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53136. var BABYLON;
  53137. (function (BABYLON) {
  53138. var SwitchBooleanAction = /** @class */ (function (_super) {
  53139. __extends(SwitchBooleanAction, _super);
  53140. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53141. var _this = _super.call(this, triggerOptions, condition) || this;
  53142. _this.propertyPath = propertyPath;
  53143. _this._target = _this._effectiveTarget = target;
  53144. return _this;
  53145. }
  53146. SwitchBooleanAction.prototype._prepare = function () {
  53147. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53148. this._property = this._getProperty(this.propertyPath);
  53149. };
  53150. SwitchBooleanAction.prototype.execute = function () {
  53151. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53152. };
  53153. SwitchBooleanAction.prototype.serialize = function (parent) {
  53154. return _super.prototype._serialize.call(this, {
  53155. name: "SwitchBooleanAction",
  53156. properties: [
  53157. BABYLON.Action._GetTargetProperty(this._target),
  53158. { name: "propertyPath", value: this.propertyPath }
  53159. ]
  53160. }, parent);
  53161. };
  53162. return SwitchBooleanAction;
  53163. }(BABYLON.Action));
  53164. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53165. var SetStateAction = /** @class */ (function (_super) {
  53166. __extends(SetStateAction, _super);
  53167. function SetStateAction(triggerOptions, target, value, condition) {
  53168. var _this = _super.call(this, triggerOptions, condition) || this;
  53169. _this.value = value;
  53170. _this._target = target;
  53171. return _this;
  53172. }
  53173. SetStateAction.prototype.execute = function () {
  53174. this._target.state = this.value;
  53175. };
  53176. SetStateAction.prototype.serialize = function (parent) {
  53177. return _super.prototype._serialize.call(this, {
  53178. name: "SetStateAction",
  53179. properties: [
  53180. BABYLON.Action._GetTargetProperty(this._target),
  53181. { name: "value", value: this.value }
  53182. ]
  53183. }, parent);
  53184. };
  53185. return SetStateAction;
  53186. }(BABYLON.Action));
  53187. BABYLON.SetStateAction = SetStateAction;
  53188. var SetValueAction = /** @class */ (function (_super) {
  53189. __extends(SetValueAction, _super);
  53190. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53191. var _this = _super.call(this, triggerOptions, condition) || this;
  53192. _this.propertyPath = propertyPath;
  53193. _this.value = value;
  53194. _this._target = _this._effectiveTarget = target;
  53195. return _this;
  53196. }
  53197. SetValueAction.prototype._prepare = function () {
  53198. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53199. this._property = this._getProperty(this.propertyPath);
  53200. };
  53201. SetValueAction.prototype.execute = function () {
  53202. this._effectiveTarget[this._property] = this.value;
  53203. if (this._target.markAsDirty) {
  53204. this._target.markAsDirty(this._property);
  53205. }
  53206. };
  53207. SetValueAction.prototype.serialize = function (parent) {
  53208. return _super.prototype._serialize.call(this, {
  53209. name: "SetValueAction",
  53210. properties: [
  53211. BABYLON.Action._GetTargetProperty(this._target),
  53212. { name: "propertyPath", value: this.propertyPath },
  53213. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53214. ]
  53215. }, parent);
  53216. };
  53217. return SetValueAction;
  53218. }(BABYLON.Action));
  53219. BABYLON.SetValueAction = SetValueAction;
  53220. var IncrementValueAction = /** @class */ (function (_super) {
  53221. __extends(IncrementValueAction, _super);
  53222. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53223. var _this = _super.call(this, triggerOptions, condition) || this;
  53224. _this.propertyPath = propertyPath;
  53225. _this.value = value;
  53226. _this._target = _this._effectiveTarget = target;
  53227. return _this;
  53228. }
  53229. IncrementValueAction.prototype._prepare = function () {
  53230. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53231. this._property = this._getProperty(this.propertyPath);
  53232. if (typeof this._effectiveTarget[this._property] !== "number") {
  53233. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53234. }
  53235. };
  53236. IncrementValueAction.prototype.execute = function () {
  53237. this._effectiveTarget[this._property] += this.value;
  53238. if (this._target.markAsDirty) {
  53239. this._target.markAsDirty(this._property);
  53240. }
  53241. };
  53242. IncrementValueAction.prototype.serialize = function (parent) {
  53243. return _super.prototype._serialize.call(this, {
  53244. name: "IncrementValueAction",
  53245. properties: [
  53246. BABYLON.Action._GetTargetProperty(this._target),
  53247. { name: "propertyPath", value: this.propertyPath },
  53248. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53249. ]
  53250. }, parent);
  53251. };
  53252. return IncrementValueAction;
  53253. }(BABYLON.Action));
  53254. BABYLON.IncrementValueAction = IncrementValueAction;
  53255. var PlayAnimationAction = /** @class */ (function (_super) {
  53256. __extends(PlayAnimationAction, _super);
  53257. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53258. var _this = _super.call(this, triggerOptions, condition) || this;
  53259. _this.from = from;
  53260. _this.to = to;
  53261. _this.loop = loop;
  53262. _this._target = target;
  53263. return _this;
  53264. }
  53265. PlayAnimationAction.prototype._prepare = function () {
  53266. };
  53267. PlayAnimationAction.prototype.execute = function () {
  53268. var scene = this._actionManager.getScene();
  53269. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53270. };
  53271. PlayAnimationAction.prototype.serialize = function (parent) {
  53272. return _super.prototype._serialize.call(this, {
  53273. name: "PlayAnimationAction",
  53274. properties: [
  53275. BABYLON.Action._GetTargetProperty(this._target),
  53276. { name: "from", value: String(this.from) },
  53277. { name: "to", value: String(this.to) },
  53278. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53279. ]
  53280. }, parent);
  53281. };
  53282. return PlayAnimationAction;
  53283. }(BABYLON.Action));
  53284. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53285. var StopAnimationAction = /** @class */ (function (_super) {
  53286. __extends(StopAnimationAction, _super);
  53287. function StopAnimationAction(triggerOptions, target, condition) {
  53288. var _this = _super.call(this, triggerOptions, condition) || this;
  53289. _this._target = target;
  53290. return _this;
  53291. }
  53292. StopAnimationAction.prototype._prepare = function () {
  53293. };
  53294. StopAnimationAction.prototype.execute = function () {
  53295. var scene = this._actionManager.getScene();
  53296. scene.stopAnimation(this._target);
  53297. };
  53298. StopAnimationAction.prototype.serialize = function (parent) {
  53299. return _super.prototype._serialize.call(this, {
  53300. name: "StopAnimationAction",
  53301. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53302. }, parent);
  53303. };
  53304. return StopAnimationAction;
  53305. }(BABYLON.Action));
  53306. BABYLON.StopAnimationAction = StopAnimationAction;
  53307. var DoNothingAction = /** @class */ (function (_super) {
  53308. __extends(DoNothingAction, _super);
  53309. function DoNothingAction(triggerOptions, condition) {
  53310. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53311. return _super.call(this, triggerOptions, condition) || this;
  53312. }
  53313. DoNothingAction.prototype.execute = function () {
  53314. };
  53315. DoNothingAction.prototype.serialize = function (parent) {
  53316. return _super.prototype._serialize.call(this, {
  53317. name: "DoNothingAction",
  53318. properties: []
  53319. }, parent);
  53320. };
  53321. return DoNothingAction;
  53322. }(BABYLON.Action));
  53323. BABYLON.DoNothingAction = DoNothingAction;
  53324. var CombineAction = /** @class */ (function (_super) {
  53325. __extends(CombineAction, _super);
  53326. function CombineAction(triggerOptions, children, condition) {
  53327. var _this = _super.call(this, triggerOptions, condition) || this;
  53328. _this.children = children;
  53329. return _this;
  53330. }
  53331. CombineAction.prototype._prepare = function () {
  53332. for (var index = 0; index < this.children.length; index++) {
  53333. this.children[index]._actionManager = this._actionManager;
  53334. this.children[index]._prepare();
  53335. }
  53336. };
  53337. CombineAction.prototype.execute = function (evt) {
  53338. for (var index = 0; index < this.children.length; index++) {
  53339. this.children[index].execute(evt);
  53340. }
  53341. };
  53342. CombineAction.prototype.serialize = function (parent) {
  53343. var serializationObject = _super.prototype._serialize.call(this, {
  53344. name: "CombineAction",
  53345. properties: [],
  53346. combine: []
  53347. }, parent);
  53348. for (var i = 0; i < this.children.length; i++) {
  53349. serializationObject.combine.push(this.children[i].serialize(null));
  53350. }
  53351. return serializationObject;
  53352. };
  53353. return CombineAction;
  53354. }(BABYLON.Action));
  53355. BABYLON.CombineAction = CombineAction;
  53356. var ExecuteCodeAction = /** @class */ (function (_super) {
  53357. __extends(ExecuteCodeAction, _super);
  53358. function ExecuteCodeAction(triggerOptions, func, condition) {
  53359. var _this = _super.call(this, triggerOptions, condition) || this;
  53360. _this.func = func;
  53361. return _this;
  53362. }
  53363. ExecuteCodeAction.prototype.execute = function (evt) {
  53364. this.func(evt);
  53365. };
  53366. return ExecuteCodeAction;
  53367. }(BABYLON.Action));
  53368. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53369. var SetParentAction = /** @class */ (function (_super) {
  53370. __extends(SetParentAction, _super);
  53371. function SetParentAction(triggerOptions, target, parent, condition) {
  53372. var _this = _super.call(this, triggerOptions, condition) || this;
  53373. _this._target = target;
  53374. _this._parent = parent;
  53375. return _this;
  53376. }
  53377. SetParentAction.prototype._prepare = function () {
  53378. };
  53379. SetParentAction.prototype.execute = function () {
  53380. if (this._target.parent === this._parent) {
  53381. return;
  53382. }
  53383. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53384. invertParentWorldMatrix.invert();
  53385. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53386. this._target.parent = this._parent;
  53387. };
  53388. SetParentAction.prototype.serialize = function (parent) {
  53389. return _super.prototype._serialize.call(this, {
  53390. name: "SetParentAction",
  53391. properties: [
  53392. BABYLON.Action._GetTargetProperty(this._target),
  53393. BABYLON.Action._GetTargetProperty(this._parent),
  53394. ]
  53395. }, parent);
  53396. };
  53397. return SetParentAction;
  53398. }(BABYLON.Action));
  53399. BABYLON.SetParentAction = SetParentAction;
  53400. var PlaySoundAction = /** @class */ (function (_super) {
  53401. __extends(PlaySoundAction, _super);
  53402. function PlaySoundAction(triggerOptions, sound, condition) {
  53403. var _this = _super.call(this, triggerOptions, condition) || this;
  53404. _this._sound = sound;
  53405. return _this;
  53406. }
  53407. PlaySoundAction.prototype._prepare = function () {
  53408. };
  53409. PlaySoundAction.prototype.execute = function () {
  53410. if (this._sound !== undefined)
  53411. this._sound.play();
  53412. };
  53413. PlaySoundAction.prototype.serialize = function (parent) {
  53414. return _super.prototype._serialize.call(this, {
  53415. name: "PlaySoundAction",
  53416. properties: [{ name: "sound", value: this._sound.name }]
  53417. }, parent);
  53418. };
  53419. return PlaySoundAction;
  53420. }(BABYLON.Action));
  53421. BABYLON.PlaySoundAction = PlaySoundAction;
  53422. var StopSoundAction = /** @class */ (function (_super) {
  53423. __extends(StopSoundAction, _super);
  53424. function StopSoundAction(triggerOptions, sound, condition) {
  53425. var _this = _super.call(this, triggerOptions, condition) || this;
  53426. _this._sound = sound;
  53427. return _this;
  53428. }
  53429. StopSoundAction.prototype._prepare = function () {
  53430. };
  53431. StopSoundAction.prototype.execute = function () {
  53432. if (this._sound !== undefined)
  53433. this._sound.stop();
  53434. };
  53435. StopSoundAction.prototype.serialize = function (parent) {
  53436. return _super.prototype._serialize.call(this, {
  53437. name: "StopSoundAction",
  53438. properties: [{ name: "sound", value: this._sound.name }]
  53439. }, parent);
  53440. };
  53441. return StopSoundAction;
  53442. }(BABYLON.Action));
  53443. BABYLON.StopSoundAction = StopSoundAction;
  53444. })(BABYLON || (BABYLON = {}));
  53445. //# sourceMappingURL=babylon.directActions.js.map
  53446. var BABYLON;
  53447. (function (BABYLON) {
  53448. var SpriteManager = /** @class */ (function () {
  53449. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53450. if (epsilon === void 0) { epsilon = 0.01; }
  53451. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53452. this.name = name;
  53453. this.sprites = new Array();
  53454. this.renderingGroupId = 0;
  53455. this.layerMask = 0x0FFFFFFF;
  53456. this.fogEnabled = true;
  53457. this.isPickable = false;
  53458. /**
  53459. * An event triggered when the manager is disposed.
  53460. */
  53461. this.onDisposeObservable = new BABYLON.Observable();
  53462. this._vertexBuffers = {};
  53463. this._capacity = capacity;
  53464. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53465. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53466. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53467. if (cellSize.width && cellSize.height) {
  53468. this.cellWidth = cellSize.width;
  53469. this.cellHeight = cellSize.height;
  53470. }
  53471. else if (cellSize !== undefined) {
  53472. this.cellWidth = cellSize;
  53473. this.cellHeight = cellSize;
  53474. }
  53475. else {
  53476. return;
  53477. }
  53478. this._epsilon = epsilon;
  53479. this._scene = scene;
  53480. this._scene.spriteManagers.push(this);
  53481. var indices = [];
  53482. var index = 0;
  53483. for (var count = 0; count < capacity; count++) {
  53484. indices.push(index);
  53485. indices.push(index + 1);
  53486. indices.push(index + 2);
  53487. indices.push(index);
  53488. indices.push(index + 2);
  53489. indices.push(index + 3);
  53490. index += 4;
  53491. }
  53492. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53493. // VBO
  53494. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53495. this._vertexData = new Float32Array(capacity * 16 * 4);
  53496. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53497. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53498. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53499. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53500. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53501. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53502. this._vertexBuffers["options"] = options;
  53503. this._vertexBuffers["cellInfo"] = cellInfo;
  53504. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53505. // Effects
  53506. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53507. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53508. }
  53509. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53510. set: function (callback) {
  53511. if (this._onDisposeObserver) {
  53512. this.onDisposeObservable.remove(this._onDisposeObserver);
  53513. }
  53514. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53515. },
  53516. enumerable: true,
  53517. configurable: true
  53518. });
  53519. Object.defineProperty(SpriteManager.prototype, "texture", {
  53520. get: function () {
  53521. return this._spriteTexture;
  53522. },
  53523. set: function (value) {
  53524. this._spriteTexture = value;
  53525. },
  53526. enumerable: true,
  53527. configurable: true
  53528. });
  53529. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53530. var arrayOffset = index * 16;
  53531. if (offsetX === 0)
  53532. offsetX = this._epsilon;
  53533. else if (offsetX === 1)
  53534. offsetX = 1 - this._epsilon;
  53535. if (offsetY === 0)
  53536. offsetY = this._epsilon;
  53537. else if (offsetY === 1)
  53538. offsetY = 1 - this._epsilon;
  53539. this._vertexData[arrayOffset] = sprite.position.x;
  53540. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53541. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53542. this._vertexData[arrayOffset + 3] = sprite.angle;
  53543. this._vertexData[arrayOffset + 4] = sprite.width;
  53544. this._vertexData[arrayOffset + 5] = sprite.height;
  53545. this._vertexData[arrayOffset + 6] = offsetX;
  53546. this._vertexData[arrayOffset + 7] = offsetY;
  53547. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53548. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53549. var offset = (sprite.cellIndex / rowSize) >> 0;
  53550. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53551. this._vertexData[arrayOffset + 11] = offset;
  53552. // Color
  53553. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53554. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53555. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53556. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53557. };
  53558. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53559. var count = Math.min(this._capacity, this.sprites.length);
  53560. var min = BABYLON.Vector3.Zero();
  53561. var max = BABYLON.Vector3.Zero();
  53562. var distance = Number.MAX_VALUE;
  53563. var currentSprite = null;
  53564. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53565. var cameraView = camera.getViewMatrix();
  53566. for (var index = 0; index < count; index++) {
  53567. var sprite = this.sprites[index];
  53568. if (!sprite) {
  53569. continue;
  53570. }
  53571. if (predicate) {
  53572. if (!predicate(sprite)) {
  53573. continue;
  53574. }
  53575. }
  53576. else if (!sprite.isPickable) {
  53577. continue;
  53578. }
  53579. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53580. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53581. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53582. if (ray.intersectsBoxMinMax(min, max)) {
  53583. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53584. if (distance > currentDistance) {
  53585. distance = currentDistance;
  53586. currentSprite = sprite;
  53587. if (fastCheck) {
  53588. break;
  53589. }
  53590. }
  53591. }
  53592. }
  53593. if (currentSprite) {
  53594. var result = new BABYLON.PickingInfo();
  53595. result.hit = true;
  53596. result.pickedSprite = currentSprite;
  53597. result.distance = distance;
  53598. return result;
  53599. }
  53600. return null;
  53601. };
  53602. SpriteManager.prototype.render = function () {
  53603. // Check
  53604. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53605. return;
  53606. var engine = this._scene.getEngine();
  53607. var baseSize = this._spriteTexture.getBaseSize();
  53608. // Sprites
  53609. var deltaTime = engine.getDeltaTime();
  53610. var max = Math.min(this._capacity, this.sprites.length);
  53611. var rowSize = baseSize.width / this.cellWidth;
  53612. var offset = 0;
  53613. for (var index = 0; index < max; index++) {
  53614. var sprite = this.sprites[index];
  53615. if (!sprite || !sprite.isVisible) {
  53616. continue;
  53617. }
  53618. sprite._animate(deltaTime);
  53619. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53620. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53621. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53622. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53623. }
  53624. this._buffer.update(this._vertexData);
  53625. // Render
  53626. var effect = this._effectBase;
  53627. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53628. effect = this._effectFog;
  53629. }
  53630. engine.enableEffect(effect);
  53631. var viewMatrix = this._scene.getViewMatrix();
  53632. effect.setTexture("diffuseSampler", this._spriteTexture);
  53633. effect.setMatrix("view", viewMatrix);
  53634. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53635. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53636. // Fog
  53637. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53638. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53639. effect.setColor3("vFogColor", this._scene.fogColor);
  53640. }
  53641. // VBOs
  53642. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53643. // Draw order
  53644. engine.setDepthFunctionToLessOrEqual();
  53645. effect.setBool("alphaTest", true);
  53646. engine.setColorWrite(false);
  53647. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53648. engine.setColorWrite(true);
  53649. effect.setBool("alphaTest", false);
  53650. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53651. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53652. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53653. };
  53654. SpriteManager.prototype.dispose = function () {
  53655. if (this._buffer) {
  53656. this._buffer.dispose();
  53657. this._buffer = null;
  53658. }
  53659. if (this._indexBuffer) {
  53660. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53661. this._indexBuffer = null;
  53662. }
  53663. if (this._spriteTexture) {
  53664. this._spriteTexture.dispose();
  53665. this._spriteTexture = null;
  53666. }
  53667. // Remove from scene
  53668. var index = this._scene.spriteManagers.indexOf(this);
  53669. this._scene.spriteManagers.splice(index, 1);
  53670. // Callback
  53671. this.onDisposeObservable.notifyObservers(this);
  53672. this.onDisposeObservable.clear();
  53673. };
  53674. return SpriteManager;
  53675. }());
  53676. BABYLON.SpriteManager = SpriteManager;
  53677. })(BABYLON || (BABYLON = {}));
  53678. //# sourceMappingURL=babylon.spriteManager.js.map
  53679. var BABYLON;
  53680. (function (BABYLON) {
  53681. var Sprite = /** @class */ (function () {
  53682. function Sprite(name, manager) {
  53683. this.name = name;
  53684. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53685. this.width = 1.0;
  53686. this.height = 1.0;
  53687. this.angle = 0;
  53688. this.cellIndex = 0;
  53689. this.invertU = 0;
  53690. this.invertV = 0;
  53691. this.animations = new Array();
  53692. this.isPickable = false;
  53693. this._animationStarted = false;
  53694. this._loopAnimation = false;
  53695. this._fromIndex = 0;
  53696. this._toIndex = 0;
  53697. this._delay = 0;
  53698. this._direction = 1;
  53699. this._time = 0;
  53700. /**
  53701. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53702. */
  53703. this.isVisible = true;
  53704. this._manager = manager;
  53705. this._manager.sprites.push(this);
  53706. this.position = BABYLON.Vector3.Zero();
  53707. }
  53708. Object.defineProperty(Sprite.prototype, "size", {
  53709. get: function () {
  53710. return this.width;
  53711. },
  53712. set: function (value) {
  53713. this.width = value;
  53714. this.height = value;
  53715. },
  53716. enumerable: true,
  53717. configurable: true
  53718. });
  53719. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53720. this._fromIndex = from;
  53721. this._toIndex = to;
  53722. this._loopAnimation = loop;
  53723. this._delay = delay;
  53724. this._animationStarted = true;
  53725. this._direction = from < to ? 1 : -1;
  53726. this.cellIndex = from;
  53727. this._time = 0;
  53728. this._onAnimationEnd = onAnimationEnd;
  53729. };
  53730. Sprite.prototype.stopAnimation = function () {
  53731. this._animationStarted = false;
  53732. };
  53733. Sprite.prototype._animate = function (deltaTime) {
  53734. if (!this._animationStarted)
  53735. return;
  53736. this._time += deltaTime;
  53737. if (this._time > this._delay) {
  53738. this._time = this._time % this._delay;
  53739. this.cellIndex += this._direction;
  53740. if (this.cellIndex > this._toIndex) {
  53741. if (this._loopAnimation) {
  53742. this.cellIndex = this._fromIndex;
  53743. }
  53744. else {
  53745. this.cellIndex = this._toIndex;
  53746. this._animationStarted = false;
  53747. if (this._onAnimationEnd) {
  53748. this._onAnimationEnd();
  53749. }
  53750. if (this.disposeWhenFinishedAnimating) {
  53751. this.dispose();
  53752. }
  53753. }
  53754. }
  53755. }
  53756. };
  53757. Sprite.prototype.dispose = function () {
  53758. for (var i = 0; i < this._manager.sprites.length; i++) {
  53759. if (this._manager.sprites[i] == this) {
  53760. this._manager.sprites.splice(i, 1);
  53761. }
  53762. }
  53763. };
  53764. return Sprite;
  53765. }());
  53766. BABYLON.Sprite = Sprite;
  53767. })(BABYLON || (BABYLON = {}));
  53768. //# sourceMappingURL=babylon.sprite.js.map
  53769. var BABYLON;
  53770. (function (BABYLON) {
  53771. var IntersectionInfo = /** @class */ (function () {
  53772. function IntersectionInfo(bu, bv, distance) {
  53773. this.bu = bu;
  53774. this.bv = bv;
  53775. this.distance = distance;
  53776. this.faceId = 0;
  53777. this.subMeshId = 0;
  53778. }
  53779. return IntersectionInfo;
  53780. }());
  53781. BABYLON.IntersectionInfo = IntersectionInfo;
  53782. /**
  53783. * Information about the result of picking within a scene
  53784. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53785. */
  53786. var PickingInfo = /** @class */ (function () {
  53787. function PickingInfo() {
  53788. /**
  53789. * If the pick collided with an object
  53790. */
  53791. this.hit = false;
  53792. /**
  53793. * Distance away where the pick collided
  53794. */
  53795. this.distance = 0;
  53796. /**
  53797. * The location of pick collision
  53798. */
  53799. this.pickedPoint = null;
  53800. /**
  53801. * The mesh corrisponding the the pick collision
  53802. */
  53803. this.pickedMesh = null;
  53804. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53805. this.bu = 0;
  53806. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53807. this.bv = 0;
  53808. /** The id of the face on the mesh that was picked */
  53809. this.faceId = -1;
  53810. /** Id of the the submesh that was picked */
  53811. this.subMeshId = 0;
  53812. /** If a sprite was picked, this will be the sprite the pick collided with */
  53813. this.pickedSprite = null;
  53814. /**
  53815. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53816. */
  53817. this.originMesh = null;
  53818. /**
  53819. * The ray that was used to perform the picking.
  53820. */
  53821. this.ray = null;
  53822. }
  53823. /**
  53824. * Gets the normal corrispodning to the face the pick collided with
  53825. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53826. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53827. * @returns The normal corrispodning to the face the pick collided with
  53828. */
  53829. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53830. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53831. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53832. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53833. return null;
  53834. }
  53835. var indices = this.pickedMesh.getIndices();
  53836. if (!indices) {
  53837. return null;
  53838. }
  53839. var result;
  53840. if (useVerticesNormals) {
  53841. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53842. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53843. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53844. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53845. normal0 = normal0.scale(this.bu);
  53846. normal1 = normal1.scale(this.bv);
  53847. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53848. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53849. }
  53850. else {
  53851. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53852. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53853. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53854. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53855. var p1p2 = vertex1.subtract(vertex2);
  53856. var p3p2 = vertex3.subtract(vertex2);
  53857. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53858. }
  53859. if (useWorldCoordinates) {
  53860. var wm = this.pickedMesh.getWorldMatrix();
  53861. if (this.pickedMesh.nonUniformScaling) {
  53862. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53863. wm = BABYLON.Tmp.Matrix[0];
  53864. wm.setTranslationFromFloats(0, 0, 0);
  53865. wm.invert();
  53866. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53867. wm = BABYLON.Tmp.Matrix[1];
  53868. }
  53869. result = BABYLON.Vector3.TransformNormal(result, wm);
  53870. }
  53871. result.normalize();
  53872. return result;
  53873. };
  53874. /**
  53875. * Gets the texture coordinates of where the pick occured
  53876. * @returns the vector containing the coordnates of the texture
  53877. */
  53878. PickingInfo.prototype.getTextureCoordinates = function () {
  53879. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53880. return null;
  53881. }
  53882. var indices = this.pickedMesh.getIndices();
  53883. if (!indices) {
  53884. return null;
  53885. }
  53886. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53887. if (!uvs) {
  53888. return null;
  53889. }
  53890. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53891. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53892. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53893. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53894. uv1 = uv1.scale(this.bu);
  53895. uv2 = uv2.scale(this.bv);
  53896. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53897. };
  53898. return PickingInfo;
  53899. }());
  53900. BABYLON.PickingInfo = PickingInfo;
  53901. })(BABYLON || (BABYLON = {}));
  53902. //# sourceMappingURL=babylon.pickingInfo.js.map
  53903. var BABYLON;
  53904. (function (BABYLON) {
  53905. var Ray = /** @class */ (function () {
  53906. function Ray(origin, direction, length) {
  53907. if (length === void 0) { length = Number.MAX_VALUE; }
  53908. this.origin = origin;
  53909. this.direction = direction;
  53910. this.length = length;
  53911. }
  53912. // Methods
  53913. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53914. var d = 0.0;
  53915. var maxValue = Number.MAX_VALUE;
  53916. var inv;
  53917. var min;
  53918. var max;
  53919. var temp;
  53920. if (Math.abs(this.direction.x) < 0.0000001) {
  53921. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53922. return false;
  53923. }
  53924. }
  53925. else {
  53926. inv = 1.0 / this.direction.x;
  53927. min = (minimum.x - this.origin.x) * inv;
  53928. max = (maximum.x - this.origin.x) * 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.y) < 0.0000001) {
  53944. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53945. return false;
  53946. }
  53947. }
  53948. else {
  53949. inv = 1.0 / this.direction.y;
  53950. min = (minimum.y - this.origin.y) * inv;
  53951. max = (maximum.y - this.origin.y) * 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. if (Math.abs(this.direction.z) < 0.0000001) {
  53967. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53968. return false;
  53969. }
  53970. }
  53971. else {
  53972. inv = 1.0 / this.direction.z;
  53973. min = (minimum.z - this.origin.z) * inv;
  53974. max = (maximum.z - this.origin.z) * inv;
  53975. if (max === -Infinity) {
  53976. max = Infinity;
  53977. }
  53978. if (min > max) {
  53979. temp = min;
  53980. min = max;
  53981. max = temp;
  53982. }
  53983. d = Math.max(min, d);
  53984. maxValue = Math.min(max, maxValue);
  53985. if (d > maxValue) {
  53986. return false;
  53987. }
  53988. }
  53989. return true;
  53990. };
  53991. Ray.prototype.intersectsBox = function (box) {
  53992. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53993. };
  53994. Ray.prototype.intersectsSphere = function (sphere) {
  53995. var x = sphere.center.x - this.origin.x;
  53996. var y = sphere.center.y - this.origin.y;
  53997. var z = sphere.center.z - this.origin.z;
  53998. var pyth = (x * x) + (y * y) + (z * z);
  53999. var rr = sphere.radius * sphere.radius;
  54000. if (pyth <= rr) {
  54001. return true;
  54002. }
  54003. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54004. if (dot < 0.0) {
  54005. return false;
  54006. }
  54007. var temp = pyth - (dot * dot);
  54008. return temp <= rr;
  54009. };
  54010. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54011. if (!this._edge1) {
  54012. this._edge1 = BABYLON.Vector3.Zero();
  54013. this._edge2 = BABYLON.Vector3.Zero();
  54014. this._pvec = BABYLON.Vector3.Zero();
  54015. this._tvec = BABYLON.Vector3.Zero();
  54016. this._qvec = BABYLON.Vector3.Zero();
  54017. }
  54018. vertex1.subtractToRef(vertex0, this._edge1);
  54019. vertex2.subtractToRef(vertex0, this._edge2);
  54020. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54021. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54022. if (det === 0) {
  54023. return null;
  54024. }
  54025. var invdet = 1 / det;
  54026. this.origin.subtractToRef(vertex0, this._tvec);
  54027. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54028. if (bu < 0 || bu > 1.0) {
  54029. return null;
  54030. }
  54031. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54032. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54033. if (bv < 0 || bu + bv > 1.0) {
  54034. return null;
  54035. }
  54036. //check if the distance is longer than the predefined length.
  54037. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54038. if (distance > this.length) {
  54039. return null;
  54040. }
  54041. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54042. };
  54043. Ray.prototype.intersectsPlane = function (plane) {
  54044. var distance;
  54045. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54046. if (Math.abs(result1) < 9.99999997475243E-07) {
  54047. return null;
  54048. }
  54049. else {
  54050. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54051. distance = (-plane.d - result2) / result1;
  54052. if (distance < 0.0) {
  54053. if (distance < -9.99999997475243E-07) {
  54054. return null;
  54055. }
  54056. else {
  54057. return 0;
  54058. }
  54059. }
  54060. return distance;
  54061. }
  54062. };
  54063. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54064. var tm = BABYLON.Tmp.Matrix[0];
  54065. mesh.getWorldMatrix().invertToRef(tm);
  54066. if (this._tmpRay) {
  54067. Ray.TransformToRef(this, tm, this._tmpRay);
  54068. }
  54069. else {
  54070. this._tmpRay = Ray.Transform(this, tm);
  54071. }
  54072. return mesh.intersects(this._tmpRay, fastCheck);
  54073. };
  54074. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54075. if (results) {
  54076. results.length = 0;
  54077. }
  54078. else {
  54079. results = [];
  54080. }
  54081. for (var i = 0; i < meshes.length; i++) {
  54082. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54083. if (pickInfo.hit) {
  54084. results.push(pickInfo);
  54085. }
  54086. }
  54087. results.sort(this._comparePickingInfo);
  54088. return results;
  54089. };
  54090. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54091. if (pickingInfoA.distance < pickingInfoB.distance) {
  54092. return -1;
  54093. }
  54094. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54095. return 1;
  54096. }
  54097. else {
  54098. return 0;
  54099. }
  54100. };
  54101. /**
  54102. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54103. * @param sega the first point of the segment to test the intersection against
  54104. * @param segb the second point of the segment to test the intersection against
  54105. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54106. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54107. */
  54108. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54109. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54110. var u = segb.subtract(sega);
  54111. var v = rsegb.subtract(this.origin);
  54112. var w = sega.subtract(this.origin);
  54113. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54114. var b = BABYLON.Vector3.Dot(u, v);
  54115. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54116. var d = BABYLON.Vector3.Dot(u, w);
  54117. var e = BABYLON.Vector3.Dot(v, w);
  54118. var D = a * c - b * b; // always >= 0
  54119. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54120. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54121. // compute the line parameters of the two closest points
  54122. if (D < Ray.smallnum) { // the lines are almost parallel
  54123. sN = 0.0; // force using point P0 on segment S1
  54124. sD = 1.0; // to prevent possible division by 0.0 later
  54125. tN = e;
  54126. tD = c;
  54127. }
  54128. else { // get the closest points on the infinite lines
  54129. sN = (b * e - c * d);
  54130. tN = (a * e - b * d);
  54131. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54132. sN = 0.0;
  54133. tN = e;
  54134. tD = c;
  54135. }
  54136. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54137. sN = sD;
  54138. tN = e + b;
  54139. tD = c;
  54140. }
  54141. }
  54142. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54143. tN = 0.0;
  54144. // recompute sc for this edge
  54145. if (-d < 0.0) {
  54146. sN = 0.0;
  54147. }
  54148. else if (-d > a)
  54149. sN = sD;
  54150. else {
  54151. sN = -d;
  54152. sD = a;
  54153. }
  54154. }
  54155. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54156. tN = tD;
  54157. // recompute sc for this edge
  54158. if ((-d + b) < 0.0) {
  54159. sN = 0;
  54160. }
  54161. else if ((-d + b) > a) {
  54162. sN = sD;
  54163. }
  54164. else {
  54165. sN = (-d + b);
  54166. sD = a;
  54167. }
  54168. }
  54169. // finally do the division to get sc and tc
  54170. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54171. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54172. // get the difference of the two closest points
  54173. var qtc = v.multiplyByFloats(tc, tc, tc);
  54174. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54175. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54176. if (isIntersected) {
  54177. return qtc.length();
  54178. }
  54179. return -1;
  54180. };
  54181. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54182. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54183. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54184. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54185. this.direction.normalize();
  54186. return this;
  54187. };
  54188. // Statics
  54189. Ray.Zero = function () {
  54190. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54191. };
  54192. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54193. var result = Ray.Zero();
  54194. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54195. };
  54196. /**
  54197. * 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
  54198. * transformed to the given world matrix.
  54199. * @param origin The origin point
  54200. * @param end The end point
  54201. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54202. */
  54203. Ray.CreateNewFromTo = function (origin, end, world) {
  54204. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54205. var direction = end.subtract(origin);
  54206. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54207. direction.normalize();
  54208. return Ray.Transform(new Ray(origin, direction, length), world);
  54209. };
  54210. Ray.Transform = function (ray, matrix) {
  54211. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54212. Ray.TransformToRef(ray, matrix, result);
  54213. return result;
  54214. };
  54215. Ray.TransformToRef = function (ray, matrix, result) {
  54216. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54217. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54218. result.length = ray.length;
  54219. var dir = result.direction;
  54220. var len = dir.length();
  54221. if (!(len === 0 || len === 1)) {
  54222. var num = 1.0 / len;
  54223. dir.x *= num;
  54224. dir.y *= num;
  54225. dir.z *= num;
  54226. result.length *= len;
  54227. }
  54228. };
  54229. Ray.smallnum = 0.00000001;
  54230. Ray.rayl = 10e8;
  54231. return Ray;
  54232. }());
  54233. BABYLON.Ray = Ray;
  54234. })(BABYLON || (BABYLON = {}));
  54235. //# sourceMappingURL=babylon.ray.js.map
  54236. var BABYLON;
  54237. (function (BABYLON) {
  54238. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54239. if (boxMin.x > sphereCenter.x + sphereRadius)
  54240. return false;
  54241. if (sphereCenter.x - sphereRadius > boxMax.x)
  54242. return false;
  54243. if (boxMin.y > sphereCenter.y + sphereRadius)
  54244. return false;
  54245. if (sphereCenter.y - sphereRadius > boxMax.y)
  54246. return false;
  54247. if (boxMin.z > sphereCenter.z + sphereRadius)
  54248. return false;
  54249. if (sphereCenter.z - sphereRadius > boxMax.z)
  54250. return false;
  54251. return true;
  54252. };
  54253. var getLowestRoot = (function () {
  54254. var result = { root: 0, found: false };
  54255. return function (a, b, c, maxR) {
  54256. result.root = 0;
  54257. result.found = false;
  54258. var determinant = b * b - 4.0 * a * c;
  54259. if (determinant < 0)
  54260. return result;
  54261. var sqrtD = Math.sqrt(determinant);
  54262. var r1 = (-b - sqrtD) / (2.0 * a);
  54263. var r2 = (-b + sqrtD) / (2.0 * a);
  54264. if (r1 > r2) {
  54265. var temp = r2;
  54266. r2 = r1;
  54267. r1 = temp;
  54268. }
  54269. if (r1 > 0 && r1 < maxR) {
  54270. result.root = r1;
  54271. result.found = true;
  54272. return result;
  54273. }
  54274. if (r2 > 0 && r2 < maxR) {
  54275. result.root = r2;
  54276. result.found = true;
  54277. return result;
  54278. }
  54279. return result;
  54280. };
  54281. })();
  54282. var Collider = /** @class */ (function () {
  54283. function Collider() {
  54284. this._collisionPoint = BABYLON.Vector3.Zero();
  54285. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54286. this._tempVector = BABYLON.Vector3.Zero();
  54287. this._tempVector2 = BABYLON.Vector3.Zero();
  54288. this._tempVector3 = BABYLON.Vector3.Zero();
  54289. this._tempVector4 = BABYLON.Vector3.Zero();
  54290. this._edge = BABYLON.Vector3.Zero();
  54291. this._baseToVertex = BABYLON.Vector3.Zero();
  54292. this._destinationPoint = BABYLON.Vector3.Zero();
  54293. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54294. this._displacementVector = BABYLON.Vector3.Zero();
  54295. this._radius = BABYLON.Vector3.One();
  54296. this._retry = 0;
  54297. this._basePointWorld = BABYLON.Vector3.Zero();
  54298. this._velocityWorld = BABYLON.Vector3.Zero();
  54299. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54300. this._collisionMask = -1;
  54301. }
  54302. Object.defineProperty(Collider.prototype, "collisionMask", {
  54303. get: function () {
  54304. return this._collisionMask;
  54305. },
  54306. set: function (mask) {
  54307. this._collisionMask = !isNaN(mask) ? mask : -1;
  54308. },
  54309. enumerable: true,
  54310. configurable: true
  54311. });
  54312. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54313. /**
  54314. * Gets the plane normal used to compute the sliding response (in local space)
  54315. */
  54316. get: function () {
  54317. return this._slidePlaneNormal;
  54318. },
  54319. enumerable: true,
  54320. configurable: true
  54321. });
  54322. // Methods
  54323. Collider.prototype._initialize = function (source, dir, e) {
  54324. this._velocity = dir;
  54325. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54326. this._basePoint = source;
  54327. source.multiplyToRef(this._radius, this._basePointWorld);
  54328. dir.multiplyToRef(this._radius, this._velocityWorld);
  54329. this._velocityWorldLength = this._velocityWorld.length();
  54330. this._epsilon = e;
  54331. this.collisionFound = false;
  54332. };
  54333. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54334. pa.subtractToRef(point, this._tempVector);
  54335. pb.subtractToRef(point, this._tempVector2);
  54336. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54337. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54338. if (d < 0)
  54339. return false;
  54340. pc.subtractToRef(point, this._tempVector3);
  54341. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54342. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54343. if (d < 0)
  54344. return false;
  54345. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54346. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54347. return d >= 0;
  54348. };
  54349. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54350. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54351. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54352. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54353. return false;
  54354. }
  54355. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54356. return false;
  54357. return true;
  54358. };
  54359. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54360. var t0;
  54361. var embeddedInPlane = false;
  54362. //defensive programming, actually not needed.
  54363. if (!trianglePlaneArray) {
  54364. trianglePlaneArray = [];
  54365. }
  54366. if (!trianglePlaneArray[faceIndex]) {
  54367. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54368. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54369. }
  54370. var trianglePlane = trianglePlaneArray[faceIndex];
  54371. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54372. return;
  54373. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54374. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54375. if (normalDotVelocity == 0) {
  54376. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54377. return;
  54378. embeddedInPlane = true;
  54379. t0 = 0;
  54380. }
  54381. else {
  54382. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54383. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54384. if (t0 > t1) {
  54385. var temp = t1;
  54386. t1 = t0;
  54387. t0 = temp;
  54388. }
  54389. if (t0 > 1.0 || t1 < 0.0)
  54390. return;
  54391. if (t0 < 0)
  54392. t0 = 0;
  54393. if (t0 > 1.0)
  54394. t0 = 1.0;
  54395. }
  54396. this._collisionPoint.copyFromFloats(0, 0, 0);
  54397. var found = false;
  54398. var t = 1.0;
  54399. if (!embeddedInPlane) {
  54400. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54401. this._velocity.scaleToRef(t0, this._tempVector);
  54402. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54403. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54404. found = true;
  54405. t = t0;
  54406. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54407. }
  54408. }
  54409. if (!found) {
  54410. var velocitySquaredLength = this._velocity.lengthSquared();
  54411. var a = velocitySquaredLength;
  54412. this._basePoint.subtractToRef(p1, this._tempVector);
  54413. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54414. var c = this._tempVector.lengthSquared() - 1.0;
  54415. var lowestRoot = getLowestRoot(a, b, c, t);
  54416. if (lowestRoot.found) {
  54417. t = lowestRoot.root;
  54418. found = true;
  54419. this._collisionPoint.copyFrom(p1);
  54420. }
  54421. this._basePoint.subtractToRef(p2, this._tempVector);
  54422. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54423. c = this._tempVector.lengthSquared() - 1.0;
  54424. lowestRoot = getLowestRoot(a, b, c, t);
  54425. if (lowestRoot.found) {
  54426. t = lowestRoot.root;
  54427. found = true;
  54428. this._collisionPoint.copyFrom(p2);
  54429. }
  54430. this._basePoint.subtractToRef(p3, this._tempVector);
  54431. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54432. c = this._tempVector.lengthSquared() - 1.0;
  54433. lowestRoot = getLowestRoot(a, b, c, t);
  54434. if (lowestRoot.found) {
  54435. t = lowestRoot.root;
  54436. found = true;
  54437. this._collisionPoint.copyFrom(p3);
  54438. }
  54439. p2.subtractToRef(p1, this._edge);
  54440. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54441. var edgeSquaredLength = this._edge.lengthSquared();
  54442. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54443. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54444. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54445. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54446. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54447. lowestRoot = getLowestRoot(a, b, c, t);
  54448. if (lowestRoot.found) {
  54449. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54450. if (f >= 0.0 && f <= 1.0) {
  54451. t = lowestRoot.root;
  54452. found = true;
  54453. this._edge.scaleInPlace(f);
  54454. p1.addToRef(this._edge, this._collisionPoint);
  54455. }
  54456. }
  54457. p3.subtractToRef(p2, this._edge);
  54458. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54459. edgeSquaredLength = this._edge.lengthSquared();
  54460. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54461. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54462. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54463. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54464. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54465. lowestRoot = getLowestRoot(a, b, c, t);
  54466. if (lowestRoot.found) {
  54467. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54468. if (f >= 0.0 && f <= 1.0) {
  54469. t = lowestRoot.root;
  54470. found = true;
  54471. this._edge.scaleInPlace(f);
  54472. p2.addToRef(this._edge, this._collisionPoint);
  54473. }
  54474. }
  54475. p1.subtractToRef(p3, this._edge);
  54476. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54477. edgeSquaredLength = this._edge.lengthSquared();
  54478. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54479. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54480. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54481. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54482. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54483. lowestRoot = getLowestRoot(a, b, c, t);
  54484. if (lowestRoot.found) {
  54485. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54486. if (f >= 0.0 && f <= 1.0) {
  54487. t = lowestRoot.root;
  54488. found = true;
  54489. this._edge.scaleInPlace(f);
  54490. p3.addToRef(this._edge, this._collisionPoint);
  54491. }
  54492. }
  54493. }
  54494. if (found) {
  54495. var distToCollision = t * this._velocity.length();
  54496. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54497. if (!this.intersectionPoint) {
  54498. this.intersectionPoint = this._collisionPoint.clone();
  54499. }
  54500. else {
  54501. this.intersectionPoint.copyFrom(this._collisionPoint);
  54502. }
  54503. this._nearestDistance = distToCollision;
  54504. this.collisionFound = true;
  54505. }
  54506. }
  54507. };
  54508. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54509. for (var i = indexStart; i < indexEnd; i += 3) {
  54510. var p1 = pts[indices[i] - decal];
  54511. var p2 = pts[indices[i + 1] - decal];
  54512. var p3 = pts[indices[i + 2] - decal];
  54513. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54514. }
  54515. };
  54516. Collider.prototype._getResponse = function (pos, vel) {
  54517. pos.addToRef(vel, this._destinationPoint);
  54518. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54519. this._basePoint.addToRef(vel, pos);
  54520. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54521. this._slidePlaneNormal.normalize();
  54522. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54523. pos.addInPlace(this._displacementVector);
  54524. this.intersectionPoint.addInPlace(this._displacementVector);
  54525. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54526. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54527. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54528. };
  54529. return Collider;
  54530. }());
  54531. BABYLON.Collider = Collider;
  54532. })(BABYLON || (BABYLON = {}));
  54533. //# sourceMappingURL=babylon.collider.js.map
  54534. var BABYLON;
  54535. (function (BABYLON) {
  54536. //WebWorker code will be inserted to this variable.
  54537. BABYLON.CollisionWorker = "";
  54538. /** Defines supported task for worker process */
  54539. var WorkerTaskType;
  54540. (function (WorkerTaskType) {
  54541. /** Initialization */
  54542. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54543. /** Update of geometry */
  54544. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54545. /** Evaluate collision */
  54546. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54547. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54548. /** Defines kind of replies returned by worker */
  54549. var WorkerReplyType;
  54550. (function (WorkerReplyType) {
  54551. /** Success */
  54552. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54553. /** Unkown error */
  54554. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54555. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54556. var CollisionCoordinatorWorker = /** @class */ (function () {
  54557. function CollisionCoordinatorWorker() {
  54558. var _this = this;
  54559. this._scaledPosition = BABYLON.Vector3.Zero();
  54560. this._scaledVelocity = BABYLON.Vector3.Zero();
  54561. this.onMeshUpdated = function (transformNode) {
  54562. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54563. };
  54564. this.onGeometryUpdated = function (geometry) {
  54565. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54566. };
  54567. this._afterRender = function () {
  54568. if (!_this._init)
  54569. return;
  54570. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54571. return;
  54572. }
  54573. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54574. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54575. if (_this._runningUpdated > 4) {
  54576. return;
  54577. }
  54578. ++_this._runningUpdated;
  54579. var payload = {
  54580. updatedMeshes: _this._addUpdateMeshesList,
  54581. updatedGeometries: _this._addUpdateGeometriesList,
  54582. removedGeometries: _this._toRemoveGeometryArray,
  54583. removedMeshes: _this._toRemoveMeshesArray
  54584. };
  54585. var message = {
  54586. payload: payload,
  54587. taskType: WorkerTaskType.UPDATE
  54588. };
  54589. var serializable = [];
  54590. for (var id in payload.updatedGeometries) {
  54591. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54592. //prepare transferables
  54593. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54594. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54595. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54596. }
  54597. }
  54598. _this._worker.postMessage(message, serializable);
  54599. _this._addUpdateMeshesList = {};
  54600. _this._addUpdateGeometriesList = {};
  54601. _this._toRemoveGeometryArray = [];
  54602. _this._toRemoveMeshesArray = [];
  54603. };
  54604. this._onMessageFromWorker = function (e) {
  54605. var returnData = e.data;
  54606. if (returnData.error != WorkerReplyType.SUCCESS) {
  54607. //TODO what errors can be returned from the worker?
  54608. BABYLON.Tools.Warn("error returned from worker!");
  54609. return;
  54610. }
  54611. switch (returnData.taskType) {
  54612. case WorkerTaskType.INIT:
  54613. _this._init = true;
  54614. //Update the worked with ALL of the scene's current state
  54615. _this._scene.meshes.forEach(function (mesh) {
  54616. _this.onMeshAdded(mesh);
  54617. });
  54618. _this._scene.getGeometries().forEach(function (geometry) {
  54619. _this.onGeometryAdded(geometry);
  54620. });
  54621. break;
  54622. case WorkerTaskType.UPDATE:
  54623. _this._runningUpdated--;
  54624. break;
  54625. case WorkerTaskType.COLLIDE:
  54626. var returnPayload = returnData.payload;
  54627. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54628. return;
  54629. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54630. if (callback) {
  54631. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54632. if (mesh) {
  54633. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54634. }
  54635. }
  54636. //cleanup
  54637. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54638. break;
  54639. }
  54640. };
  54641. this._collisionsCallbackArray = [];
  54642. this._init = false;
  54643. this._runningUpdated = 0;
  54644. this._addUpdateMeshesList = {};
  54645. this._addUpdateGeometriesList = {};
  54646. this._toRemoveGeometryArray = [];
  54647. this._toRemoveMeshesArray = [];
  54648. }
  54649. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54650. if (!this._init)
  54651. return;
  54652. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54653. return;
  54654. position.divideToRef(collider._radius, this._scaledPosition);
  54655. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54656. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54657. var payload = {
  54658. collider: {
  54659. position: this._scaledPosition.asArray(),
  54660. velocity: this._scaledVelocity.asArray(),
  54661. radius: collider._radius.asArray()
  54662. },
  54663. collisionId: collisionIndex,
  54664. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54665. maximumRetry: maximumRetry
  54666. };
  54667. var message = {
  54668. payload: payload,
  54669. taskType: WorkerTaskType.COLLIDE
  54670. };
  54671. this._worker.postMessage(message);
  54672. };
  54673. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54674. this._scene = scene;
  54675. this._scene.registerAfterRender(this._afterRender);
  54676. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54677. this._worker = new Worker(workerUrl);
  54678. this._worker.onmessage = this._onMessageFromWorker;
  54679. var message = {
  54680. payload: {},
  54681. taskType: WorkerTaskType.INIT
  54682. };
  54683. this._worker.postMessage(message);
  54684. };
  54685. CollisionCoordinatorWorker.prototype.destroy = function () {
  54686. this._scene.unregisterAfterRender(this._afterRender);
  54687. this._worker.terminate();
  54688. };
  54689. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54690. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54691. this.onMeshUpdated(mesh);
  54692. };
  54693. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54694. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54695. };
  54696. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54697. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54698. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54699. this.onGeometryUpdated(geometry);
  54700. };
  54701. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54702. this._toRemoveGeometryArray.push(geometry.id);
  54703. };
  54704. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54705. var submeshes = [];
  54706. if (mesh.subMeshes) {
  54707. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54708. var boundingInfo = sm.getBoundingInfo();
  54709. return {
  54710. position: idx,
  54711. verticesStart: sm.verticesStart,
  54712. verticesCount: sm.verticesCount,
  54713. indexStart: sm.indexStart,
  54714. indexCount: sm.indexCount,
  54715. hasMaterial: !!sm.getMaterial(),
  54716. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54717. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54718. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54719. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54720. };
  54721. });
  54722. }
  54723. var geometryId = null;
  54724. if (mesh instanceof BABYLON.Mesh) {
  54725. var geometry = mesh.geometry;
  54726. geometryId = geometry ? geometry.id : null;
  54727. }
  54728. else if (mesh instanceof BABYLON.InstancedMesh) {
  54729. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54730. geometryId = geometry ? geometry.id : null;
  54731. }
  54732. var boundingInfo = mesh.getBoundingInfo();
  54733. return {
  54734. uniqueId: mesh.uniqueId,
  54735. id: mesh.id,
  54736. name: mesh.name,
  54737. geometryId: geometryId,
  54738. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54739. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54740. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54741. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54742. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54743. subMeshes: submeshes,
  54744. checkCollisions: mesh.checkCollisions
  54745. };
  54746. };
  54747. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54748. return {
  54749. id: geometry.id,
  54750. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54751. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54752. indices: new Uint32Array(geometry.getIndices() || []),
  54753. };
  54754. };
  54755. return CollisionCoordinatorWorker;
  54756. }());
  54757. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54758. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54759. function CollisionCoordinatorLegacy() {
  54760. this._scaledPosition = BABYLON.Vector3.Zero();
  54761. this._scaledVelocity = BABYLON.Vector3.Zero();
  54762. this._finalPosition = BABYLON.Vector3.Zero();
  54763. }
  54764. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54765. position.divideToRef(collider._radius, this._scaledPosition);
  54766. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54767. collider.collidedMesh = null;
  54768. collider._retry = 0;
  54769. collider._initialVelocity = this._scaledVelocity;
  54770. collider._initialPosition = this._scaledPosition;
  54771. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54772. this._finalPosition.multiplyInPlace(collider._radius);
  54773. //run the callback
  54774. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54775. };
  54776. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54777. this._scene = scene;
  54778. };
  54779. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54780. //Legacy need no destruction method.
  54781. };
  54782. //No update in legacy mode
  54783. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54784. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54785. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54786. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54787. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54788. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54789. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54790. if (excludedMesh === void 0) { excludedMesh = null; }
  54791. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54792. if (collider._retry >= maximumRetry) {
  54793. finalPosition.copyFrom(position);
  54794. return;
  54795. }
  54796. // Check if this is a mesh else camera or -1
  54797. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54798. collider._initialize(position, velocity, closeDistance);
  54799. // Check all meshes
  54800. for (var index = 0; index < this._scene.meshes.length; index++) {
  54801. var mesh = this._scene.meshes[index];
  54802. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54803. mesh._checkCollision(collider);
  54804. }
  54805. }
  54806. if (!collider.collisionFound) {
  54807. position.addToRef(velocity, finalPosition);
  54808. return;
  54809. }
  54810. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54811. collider._getResponse(position, velocity);
  54812. }
  54813. if (velocity.length() <= closeDistance) {
  54814. finalPosition.copyFrom(position);
  54815. return;
  54816. }
  54817. collider._retry++;
  54818. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54819. };
  54820. return CollisionCoordinatorLegacy;
  54821. }());
  54822. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54823. })(BABYLON || (BABYLON = {}));
  54824. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54825. var BABYLON;
  54826. (function (BABYLON) {
  54827. /**
  54828. * A particle represents one of the element emitted by a particle system.
  54829. * This is mainly define by its coordinates, direction, velocity and age.
  54830. */
  54831. var Particle = /** @class */ (function () {
  54832. /**
  54833. * Creates a new instance Particle
  54834. * @param particleSystem the particle system the particle belongs to
  54835. */
  54836. function Particle(
  54837. /**
  54838. * particleSystem the particle system the particle belongs to.
  54839. */
  54840. particleSystem) {
  54841. this.particleSystem = particleSystem;
  54842. /**
  54843. * The world position of the particle in the scene.
  54844. */
  54845. this.position = BABYLON.Vector3.Zero();
  54846. /**
  54847. * The world direction of the particle in the scene.
  54848. */
  54849. this.direction = BABYLON.Vector3.Zero();
  54850. /**
  54851. * The color of the particle.
  54852. */
  54853. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54854. /**
  54855. * The color change of the particle per step.
  54856. */
  54857. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54858. /**
  54859. * Defines how long will the life of the particle be.
  54860. */
  54861. this.lifeTime = 1.0;
  54862. /**
  54863. * The current age of the particle.
  54864. */
  54865. this.age = 0;
  54866. /**
  54867. * The current size of the particle.
  54868. */
  54869. this.size = 0;
  54870. /**
  54871. * The current scale of the particle.
  54872. */
  54873. this.scale = new BABYLON.Vector2(1, 1);
  54874. /**
  54875. * The current angle of the particle.
  54876. */
  54877. this.angle = 0;
  54878. /**
  54879. * Defines how fast is the angle changing.
  54880. */
  54881. this.angularSpeed = 0;
  54882. /**
  54883. * Defines the cell index used by the particle to be rendered from a sprite.
  54884. */
  54885. this.cellIndex = 0;
  54886. /** @hidden */
  54887. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54888. /** @hidden */
  54889. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54890. /** @hidden */
  54891. this._currentSize1 = 0;
  54892. /** @hidden */
  54893. this._currentSize2 = 0;
  54894. /** @hidden */
  54895. this._currentAngularSpeed1 = 0;
  54896. /** @hidden */
  54897. this._currentAngularSpeed2 = 0;
  54898. /** @hidden */
  54899. this._currentVelocity1 = 0;
  54900. /** @hidden */
  54901. this._currentVelocity2 = 0;
  54902. if (!this.particleSystem.isAnimationSheetEnabled) {
  54903. return;
  54904. }
  54905. this.updateCellInfoFromSystem();
  54906. }
  54907. Particle.prototype.updateCellInfoFromSystem = function () {
  54908. this.cellIndex = this.particleSystem.startSpriteCellID;
  54909. };
  54910. /**
  54911. * Defines how the sprite cell index is updated for the particle
  54912. */
  54913. Particle.prototype.updateCellIndex = function () {
  54914. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54915. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54916. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54917. };
  54918. /**
  54919. * Copy the properties of particle to another one.
  54920. * @param other the particle to copy the information to.
  54921. */
  54922. Particle.prototype.copyTo = function (other) {
  54923. other.position.copyFrom(this.position);
  54924. if (this._initialDirection) {
  54925. if (other._initialDirection) {
  54926. other._initialDirection.copyFrom(this._initialDirection);
  54927. }
  54928. else {
  54929. other._initialDirection = this._initialDirection.clone();
  54930. }
  54931. }
  54932. else {
  54933. other._initialDirection = null;
  54934. }
  54935. other.direction.copyFrom(this.direction);
  54936. other.color.copyFrom(this.color);
  54937. other.colorStep.copyFrom(this.colorStep);
  54938. other.lifeTime = this.lifeTime;
  54939. other.age = this.age;
  54940. other.size = this.size;
  54941. other.scale.copyFrom(this.scale);
  54942. other.angle = this.angle;
  54943. other.angularSpeed = this.angularSpeed;
  54944. other.particleSystem = this.particleSystem;
  54945. other.cellIndex = this.cellIndex;
  54946. if (this._currentColorGradient) {
  54947. other._currentColorGradient = this._currentColorGradient;
  54948. other._currentColor1.copyFrom(this._currentColor1);
  54949. other._currentColor2.copyFrom(this._currentColor2);
  54950. }
  54951. if (this._currentSizeGradient) {
  54952. other._currentSizeGradient = this._currentSizeGradient;
  54953. other._currentSize1 = this._currentSize1;
  54954. other._currentSize2 = this._currentSize2;
  54955. }
  54956. if (this._currentAngularSpeedGradient) {
  54957. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54958. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54959. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54960. }
  54961. if (this._currentVelocityGradient) {
  54962. other._currentVelocityGradient = this._currentVelocityGradient;
  54963. other._currentVelocity1 = this._currentVelocity1;
  54964. other._currentVelocity2 = this._currentVelocity2;
  54965. }
  54966. if (this.particleSystem.isAnimationSheetEnabled) {
  54967. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54968. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54969. }
  54970. };
  54971. return Particle;
  54972. }());
  54973. BABYLON.Particle = Particle;
  54974. })(BABYLON || (BABYLON = {}));
  54975. //# sourceMappingURL=babylon.particle.js.map
  54976. var BABYLON;
  54977. (function (BABYLON) {
  54978. /**
  54979. * This represents a particle system in Babylon.
  54980. * 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.
  54981. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54982. * @example https://doc.babylonjs.com/babylon101/particles
  54983. */
  54984. var ParticleSystem = /** @class */ (function () {
  54985. /**
  54986. * Instantiates a particle system.
  54987. * 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.
  54988. * @param name The name of the particle system
  54989. * @param capacity The max number of particles alive at the same time
  54990. * @param scene The scene the particle system belongs to
  54991. * @param customEffect a custom effect used to change the way particles are rendered by default
  54992. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54993. * @param epsilon Offset used to render the particles
  54994. */
  54995. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54996. if (customEffect === void 0) { customEffect = null; }
  54997. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54998. if (epsilon === void 0) { epsilon = 0.01; }
  54999. var _this = this;
  55000. /**
  55001. * List of animations used by the particle system.
  55002. */
  55003. this.animations = [];
  55004. /**
  55005. * The rendering group used by the Particle system to chose when to render.
  55006. */
  55007. this.renderingGroupId = 0;
  55008. /**
  55009. * The emitter represents the Mesh or position we are attaching the particle system to.
  55010. */
  55011. this.emitter = null;
  55012. /**
  55013. * The maximum number of particles to emit per frame
  55014. */
  55015. this.emitRate = 10;
  55016. /**
  55017. * If you want to launch only a few particles at once, that can be done, as well.
  55018. */
  55019. this.manualEmitCount = -1;
  55020. /**
  55021. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55022. */
  55023. this.updateSpeed = 0.01;
  55024. /**
  55025. * The amount of time the particle system is running (depends of the overall update speed).
  55026. */
  55027. this.targetStopDuration = 0;
  55028. /**
  55029. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55030. */
  55031. this.disposeOnStop = false;
  55032. /**
  55033. * Minimum power of emitting particles.
  55034. */
  55035. this.minEmitPower = 1;
  55036. /**
  55037. * Maximum power of emitting particles.
  55038. */
  55039. this.maxEmitPower = 1;
  55040. /**
  55041. * Minimum life time of emitting particles.
  55042. */
  55043. this.minLifeTime = 1;
  55044. /**
  55045. * Maximum life time of emitting particles.
  55046. */
  55047. this.maxLifeTime = 1;
  55048. /**
  55049. * Minimum Size of emitting particles.
  55050. */
  55051. this.minSize = 1;
  55052. /**
  55053. * Maximum Size of emitting particles.
  55054. */
  55055. this.maxSize = 1;
  55056. /**
  55057. * Minimum scale of emitting particles on X axis.
  55058. */
  55059. this.minScaleX = 1;
  55060. /**
  55061. * Maximum scale of emitting particles on X axis.
  55062. */
  55063. this.maxScaleX = 1;
  55064. /**
  55065. * Minimum scale of emitting particles on Y axis.
  55066. */
  55067. this.minScaleY = 1;
  55068. /**
  55069. * Maximum scale of emitting particles on Y axis.
  55070. */
  55071. this.maxScaleY = 1;
  55072. /**
  55073. * Gets or sets the minimal initial rotation in radians.
  55074. */
  55075. this.minInitialRotation = 0;
  55076. /**
  55077. * Gets or sets the maximal initial rotation in radians.
  55078. */
  55079. this.maxInitialRotation = 0;
  55080. /**
  55081. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55082. */
  55083. this.minAngularSpeed = 0;
  55084. /**
  55085. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55086. */
  55087. this.maxAngularSpeed = 0;
  55088. /**
  55089. * The layer mask we are rendering the particles through.
  55090. */
  55091. this.layerMask = 0x0FFFFFFF;
  55092. /**
  55093. * This can help using your own shader to render the particle system.
  55094. * The according effect will be created
  55095. */
  55096. this.customShader = null;
  55097. /**
  55098. * By default particle system starts as soon as they are created. This prevents the
  55099. * automatic start to happen and let you decide when to start emitting particles.
  55100. */
  55101. this.preventAutoStart = false;
  55102. /**
  55103. * Callback triggered when the particle animation is ending.
  55104. */
  55105. this.onAnimationEnd = null;
  55106. /**
  55107. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55108. */
  55109. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55110. /**
  55111. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55112. * to override the particles.
  55113. */
  55114. this.forceDepthWrite = false;
  55115. /**
  55116. * You can use gravity if you want to give an orientation to your particles.
  55117. */
  55118. this.gravity = BABYLON.Vector3.Zero();
  55119. this._colorGradients = null;
  55120. this._sizeGradients = null;
  55121. this._lifeTimeGradients = null;
  55122. this._angularSpeedGradients = null;
  55123. this._velocityGradients = null;
  55124. /**
  55125. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55126. */
  55127. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55128. /**
  55129. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55130. */
  55131. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55132. /**
  55133. * Color the particle will have at the end of its lifetime
  55134. */
  55135. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55136. /**
  55137. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55138. */
  55139. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55140. /**
  55141. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55142. */
  55143. this.spriteCellChangeSpeed = 1;
  55144. /**
  55145. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55146. */
  55147. this.startSpriteCellID = 0;
  55148. /**
  55149. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55150. */
  55151. this.endSpriteCellID = 0;
  55152. /**
  55153. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55154. */
  55155. this.spriteCellWidth = 0;
  55156. /**
  55157. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55158. */
  55159. this.spriteCellHeight = 0;
  55160. /** 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 */
  55161. this.preWarmCycles = 0;
  55162. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55163. this.preWarmStepOffset = 1;
  55164. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55165. this.translationPivot = new BABYLON.Vector2(0, 0);
  55166. /**
  55167. * An event triggered when the system is disposed
  55168. */
  55169. this.onDisposeObservable = new BABYLON.Observable();
  55170. /**
  55171. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55172. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55173. */
  55174. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55175. this._particles = new Array();
  55176. this._stockParticles = new Array();
  55177. this._newPartsExcess = 0;
  55178. this._vertexBuffers = {};
  55179. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55180. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55181. this._scaledDirection = BABYLON.Vector3.Zero();
  55182. this._scaledGravity = BABYLON.Vector3.Zero();
  55183. this._currentRenderId = -1;
  55184. this._useInstancing = false;
  55185. this._started = false;
  55186. this._stopped = false;
  55187. this._actualFrame = 0;
  55188. this._isBillboardBased = true;
  55189. // start of sub system methods
  55190. /**
  55191. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55192. * Its lifetime will start back at 0.
  55193. */
  55194. this.recycleParticle = function (particle) {
  55195. var lastParticle = _this._particles.pop();
  55196. if (lastParticle !== particle) {
  55197. lastParticle.copyTo(particle);
  55198. }
  55199. _this._stockParticles.push(lastParticle);
  55200. };
  55201. this._createParticle = function () {
  55202. var particle;
  55203. if (_this._stockParticles.length !== 0) {
  55204. particle = _this._stockParticles.pop();
  55205. particle.age = 0;
  55206. particle._currentColorGradient = null;
  55207. particle.cellIndex = _this.startSpriteCellID;
  55208. }
  55209. else {
  55210. particle = new BABYLON.Particle(_this);
  55211. }
  55212. return particle;
  55213. };
  55214. this._emitFromParticle = function (particle) {
  55215. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55216. return;
  55217. }
  55218. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55219. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55220. subSystem._rootParticleSystem = _this;
  55221. _this.activeSubSystems.push(subSystem);
  55222. subSystem.start();
  55223. };
  55224. this.id = name;
  55225. this.name = name;
  55226. this._capacity = capacity;
  55227. this._epsilon = epsilon;
  55228. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55229. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55230. this._customEffect = customEffect;
  55231. scene.particleSystems.push(this);
  55232. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55233. this._createIndexBuffer();
  55234. this._createVertexBuffers();
  55235. // Default emitter type
  55236. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55237. this.updateFunction = function (particles) {
  55238. var _loop_1 = function () {
  55239. particle = particles[index];
  55240. particle.age += _this._scaledUpdateSpeed;
  55241. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55242. _this._emitFromParticle(particle);
  55243. _this.recycleParticle(particle);
  55244. index--;
  55245. return "continue";
  55246. }
  55247. else {
  55248. var ratio = particle.age / particle.lifeTime;
  55249. // Color
  55250. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55251. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55252. if (currentGradient !== particle._currentColorGradient) {
  55253. particle._currentColor1.copyFrom(particle._currentColor2);
  55254. nextGradient.getColorToRef(particle._currentColor2);
  55255. particle._currentColorGradient = currentGradient;
  55256. }
  55257. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55258. });
  55259. }
  55260. else {
  55261. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55262. particle.color.addInPlace(_this._scaledColorStep);
  55263. if (particle.color.a < 0) {
  55264. particle.color.a = 0;
  55265. }
  55266. }
  55267. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55268. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55269. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55270. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55271. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55272. particle._currentAngularSpeedGradient = currentGradient;
  55273. }
  55274. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55275. });
  55276. }
  55277. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55278. var directionScale_1 = _this._scaledUpdateSpeed;
  55279. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55280. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55281. if (currentGradient !== particle._currentVelocityGradient) {
  55282. particle._currentVelocity1 = particle._currentVelocity2;
  55283. particle._currentVelocity2 = nextGradient.getFactor();
  55284. particle._currentVelocityGradient = currentGradient;
  55285. }
  55286. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55287. });
  55288. }
  55289. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55290. particle.position.addInPlace(_this._scaledDirection);
  55291. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55292. particle.direction.addInPlace(_this._scaledGravity);
  55293. // Size
  55294. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55295. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55296. if (currentGradient !== particle._currentSizeGradient) {
  55297. particle._currentSize1 = particle._currentSize2;
  55298. particle._currentSize2 = nextGradient.getFactor();
  55299. particle._currentSizeGradient = currentGradient;
  55300. }
  55301. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55302. });
  55303. }
  55304. if (_this._isAnimationSheetEnabled) {
  55305. particle.updateCellIndex();
  55306. }
  55307. }
  55308. };
  55309. var particle;
  55310. for (var index = 0; index < particles.length; index++) {
  55311. _loop_1();
  55312. }
  55313. };
  55314. }
  55315. /**
  55316. * Gets the current list of color gradients.
  55317. * You must use addColorGradient and removeColorGradient to udpate this list
  55318. * @returns the list of color gradients
  55319. */
  55320. ParticleSystem.prototype.getColorGradients = function () {
  55321. return this._colorGradients;
  55322. };
  55323. /**
  55324. * Gets the current list of size gradients.
  55325. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55326. * @returns the list of size gradients
  55327. */
  55328. ParticleSystem.prototype.getSizeGradients = function () {
  55329. return this._sizeGradients;
  55330. };
  55331. /**
  55332. * Gets the current list of life time gradients.
  55333. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55334. * @returns the list of life time gradients
  55335. */
  55336. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55337. return this._lifeTimeGradients;
  55338. };
  55339. /**
  55340. * Gets the current list of angular speed gradients.
  55341. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55342. * @returns the list of angular speed gradients
  55343. */
  55344. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55345. return this._angularSpeedGradients;
  55346. };
  55347. /**
  55348. * Gets the current list of velocity gradients.
  55349. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55350. * @returns the list of velocity gradients
  55351. */
  55352. ParticleSystem.prototype.getVelocityGradients = function () {
  55353. return this._velocityGradients;
  55354. };
  55355. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55356. /**
  55357. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55358. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55359. */
  55360. get: function () {
  55361. if (this.particleEmitterType.direction1) {
  55362. return this.particleEmitterType.direction1;
  55363. }
  55364. return BABYLON.Vector3.Zero();
  55365. },
  55366. set: function (value) {
  55367. if (this.particleEmitterType.direction1) {
  55368. this.particleEmitterType.direction1 = value;
  55369. }
  55370. },
  55371. enumerable: true,
  55372. configurable: true
  55373. });
  55374. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55375. /**
  55376. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55377. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55378. */
  55379. get: function () {
  55380. if (this.particleEmitterType.direction2) {
  55381. return this.particleEmitterType.direction2;
  55382. }
  55383. return BABYLON.Vector3.Zero();
  55384. },
  55385. set: function (value) {
  55386. if (this.particleEmitterType.direction2) {
  55387. this.particleEmitterType.direction2 = value;
  55388. }
  55389. },
  55390. enumerable: true,
  55391. configurable: true
  55392. });
  55393. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55394. /**
  55395. * 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.
  55396. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55397. */
  55398. get: function () {
  55399. if (this.particleEmitterType.minEmitBox) {
  55400. return this.particleEmitterType.minEmitBox;
  55401. }
  55402. return BABYLON.Vector3.Zero();
  55403. },
  55404. set: function (value) {
  55405. if (this.particleEmitterType.minEmitBox) {
  55406. this.particleEmitterType.minEmitBox = value;
  55407. }
  55408. },
  55409. enumerable: true,
  55410. configurable: true
  55411. });
  55412. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55413. /**
  55414. * 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.
  55415. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55416. */
  55417. get: function () {
  55418. if (this.particleEmitterType.maxEmitBox) {
  55419. return this.particleEmitterType.maxEmitBox;
  55420. }
  55421. return BABYLON.Vector3.Zero();
  55422. },
  55423. set: function (value) {
  55424. if (this.particleEmitterType.maxEmitBox) {
  55425. this.particleEmitterType.maxEmitBox = value;
  55426. }
  55427. },
  55428. enumerable: true,
  55429. configurable: true
  55430. });
  55431. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55432. /**
  55433. * Sets a callback that will be triggered when the system is disposed
  55434. */
  55435. set: function (callback) {
  55436. if (this._onDisposeObserver) {
  55437. this.onDisposeObservable.remove(this._onDisposeObserver);
  55438. }
  55439. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55440. },
  55441. enumerable: true,
  55442. configurable: true
  55443. });
  55444. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55445. /**
  55446. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55447. */
  55448. get: function () {
  55449. return this._isAnimationSheetEnabled;
  55450. },
  55451. enumerable: true,
  55452. configurable: true
  55453. });
  55454. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55455. /**
  55456. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55457. */
  55458. get: function () {
  55459. return this._isBillboardBased;
  55460. },
  55461. set: function (value) {
  55462. if (this._isBillboardBased === value) {
  55463. return;
  55464. }
  55465. this._isBillboardBased = value;
  55466. this._resetEffect();
  55467. },
  55468. enumerable: true,
  55469. configurable: true
  55470. });
  55471. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55472. //end of Sub-emitter
  55473. /**
  55474. * Gets the current list of active particles
  55475. */
  55476. get: function () {
  55477. return this._particles;
  55478. },
  55479. enumerable: true,
  55480. configurable: true
  55481. });
  55482. /**
  55483. * Returns the string "ParticleSystem"
  55484. * @returns a string containing the class name
  55485. */
  55486. ParticleSystem.prototype.getClassName = function () {
  55487. return "ParticleSystem";
  55488. };
  55489. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55490. var newGradient = new BABYLON.FactorGradient();
  55491. newGradient.gradient = gradient;
  55492. newGradient.factor1 = factor;
  55493. newGradient.factor2 = factor2;
  55494. factorGradients.push(newGradient);
  55495. factorGradients.sort(function (a, b) {
  55496. if (a.gradient < b.gradient) {
  55497. return -1;
  55498. }
  55499. else if (a.gradient > b.gradient) {
  55500. return 1;
  55501. }
  55502. return 0;
  55503. });
  55504. };
  55505. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55506. if (!factorGradients) {
  55507. return;
  55508. }
  55509. var index = 0;
  55510. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55511. var factorGradient = factorGradients_1[_i];
  55512. if (factorGradient.gradient === gradient) {
  55513. factorGradients.splice(index, 1);
  55514. break;
  55515. }
  55516. index++;
  55517. }
  55518. };
  55519. /**
  55520. * Adds a new life time gradient
  55521. * @param gradient defines the gradient to use (between 0 and 1)
  55522. * @param factor defines the life time factor to affect to the specified gradient
  55523. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55524. * @returns the current particle system
  55525. */
  55526. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55527. if (!this._lifeTimeGradients) {
  55528. this._lifeTimeGradients = [];
  55529. }
  55530. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55531. return this;
  55532. };
  55533. /**
  55534. * Remove a specific life time gradient
  55535. * @param gradient defines the gradient to remove
  55536. * @returns the current particle system
  55537. */
  55538. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55539. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55540. return this;
  55541. };
  55542. /**
  55543. * Adds a new size gradient
  55544. * @param gradient defines the gradient to use (between 0 and 1)
  55545. * @param factor defines the size factor to affect to the specified gradient
  55546. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55547. * @returns the current particle system
  55548. */
  55549. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55550. if (!this._sizeGradients) {
  55551. this._sizeGradients = [];
  55552. }
  55553. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55554. return this;
  55555. };
  55556. /**
  55557. * Remove a specific size gradient
  55558. * @param gradient defines the gradient to remove
  55559. * @returns the current particle system
  55560. */
  55561. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55562. this._removeFactorGradient(this._sizeGradients, gradient);
  55563. return this;
  55564. };
  55565. /**
  55566. * Adds a new angular speed gradient
  55567. * @param gradient defines the gradient to use (between 0 and 1)
  55568. * @param factor defines the size factor to affect to the specified gradient
  55569. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55570. * @returns the current particle system
  55571. */
  55572. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55573. if (!this._angularSpeedGradients) {
  55574. this._angularSpeedGradients = [];
  55575. }
  55576. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55577. return this;
  55578. };
  55579. /**
  55580. * Remove a specific angular speed gradient
  55581. * @param gradient defines the gradient to remove
  55582. * @returns the current particle system
  55583. */
  55584. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55585. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55586. return this;
  55587. };
  55588. /**
  55589. * Adds a new velocity gradient
  55590. * @param gradient defines the gradient to use (between 0 and 1)
  55591. * @param factor defines the size factor to affect to the specified gradient
  55592. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55593. * @returns the current particle system
  55594. */
  55595. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55596. if (!this._velocityGradients) {
  55597. this._velocityGradients = [];
  55598. }
  55599. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55600. return this;
  55601. };
  55602. /**
  55603. * Remove a specific velocity gradient
  55604. * @param gradient defines the gradient to remove
  55605. * @returns the current particle system
  55606. */
  55607. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55608. this._removeFactorGradient(this._velocityGradients, gradient);
  55609. return this;
  55610. };
  55611. /**
  55612. * Adds a new color gradient
  55613. * @param gradient defines the gradient to use (between 0 and 1)
  55614. * @param color defines the color to affect to the specified gradient
  55615. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55616. */
  55617. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55618. if (!this._colorGradients) {
  55619. this._colorGradients = [];
  55620. }
  55621. var colorGradient = new BABYLON.ColorGradient();
  55622. colorGradient.gradient = gradient;
  55623. colorGradient.color1 = color;
  55624. colorGradient.color2 = color2;
  55625. this._colorGradients.push(colorGradient);
  55626. this._colorGradients.sort(function (a, b) {
  55627. if (a.gradient < b.gradient) {
  55628. return -1;
  55629. }
  55630. else if (a.gradient > b.gradient) {
  55631. return 1;
  55632. }
  55633. return 0;
  55634. });
  55635. return this;
  55636. };
  55637. /**
  55638. * Remove a specific color gradient
  55639. * @param gradient defines the gradient to remove
  55640. */
  55641. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55642. if (!this._colorGradients) {
  55643. return this;
  55644. }
  55645. var index = 0;
  55646. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55647. var colorGradient = _a[_i];
  55648. if (colorGradient.gradient === gradient) {
  55649. this._colorGradients.splice(index, 1);
  55650. break;
  55651. }
  55652. index++;
  55653. }
  55654. return this;
  55655. };
  55656. ParticleSystem.prototype._resetEffect = function () {
  55657. if (this._vertexBuffer) {
  55658. this._vertexBuffer.dispose();
  55659. this._vertexBuffer = null;
  55660. }
  55661. if (this._spriteBuffer) {
  55662. this._spriteBuffer.dispose();
  55663. this._spriteBuffer = null;
  55664. }
  55665. this._createVertexBuffers();
  55666. };
  55667. ParticleSystem.prototype._createVertexBuffers = function () {
  55668. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55669. if (this._isAnimationSheetEnabled) {
  55670. this._vertexBufferSize += 1;
  55671. }
  55672. if (!this._isBillboardBased) {
  55673. this._vertexBufferSize += 3;
  55674. }
  55675. var engine = this._scene.getEngine();
  55676. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55677. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55678. var dataOffset = 0;
  55679. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55680. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55681. dataOffset += 3;
  55682. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55683. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55684. dataOffset += 4;
  55685. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55686. this._vertexBuffers["angle"] = options;
  55687. dataOffset += 1;
  55688. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55689. this._vertexBuffers["size"] = size;
  55690. dataOffset += 2;
  55691. if (this._isAnimationSheetEnabled) {
  55692. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55693. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55694. dataOffset += 1;
  55695. }
  55696. if (!this._isBillboardBased) {
  55697. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55698. this._vertexBuffers["direction"] = directionBuffer;
  55699. dataOffset += 3;
  55700. }
  55701. var offsets;
  55702. if (this._useInstancing) {
  55703. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55704. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55705. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55706. }
  55707. else {
  55708. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55709. dataOffset += 2;
  55710. }
  55711. this._vertexBuffers["offset"] = offsets;
  55712. };
  55713. ParticleSystem.prototype._createIndexBuffer = function () {
  55714. if (this._useInstancing) {
  55715. return;
  55716. }
  55717. var indices = [];
  55718. var index = 0;
  55719. for (var count = 0; count < this._capacity; count++) {
  55720. indices.push(index);
  55721. indices.push(index + 1);
  55722. indices.push(index + 2);
  55723. indices.push(index);
  55724. indices.push(index + 2);
  55725. indices.push(index + 3);
  55726. index += 4;
  55727. }
  55728. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55729. };
  55730. /**
  55731. * Gets the maximum number of particles active at the same time.
  55732. * @returns The max number of active particles.
  55733. */
  55734. ParticleSystem.prototype.getCapacity = function () {
  55735. return this._capacity;
  55736. };
  55737. /**
  55738. * Gets Wether there are still active particles in the system.
  55739. * @returns True if it is alive, otherwise false.
  55740. */
  55741. ParticleSystem.prototype.isAlive = function () {
  55742. return this._alive;
  55743. };
  55744. /**
  55745. * Gets Wether the system has been started.
  55746. * @returns True if it has been started, otherwise false.
  55747. */
  55748. ParticleSystem.prototype.isStarted = function () {
  55749. return this._started;
  55750. };
  55751. /**
  55752. * Starts the particle system and begins to emit.
  55753. */
  55754. ParticleSystem.prototype.start = function () {
  55755. this._started = true;
  55756. this._stopped = false;
  55757. this._actualFrame = 0;
  55758. if (this.subEmitters && this.subEmitters.length != 0) {
  55759. this.activeSubSystems = new Array();
  55760. }
  55761. if (this.preWarmCycles) {
  55762. for (var index = 0; index < this.preWarmCycles; index++) {
  55763. this.animate(true);
  55764. }
  55765. }
  55766. };
  55767. /**
  55768. * Stops the particle system.
  55769. * @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.
  55770. */
  55771. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55772. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55773. this._stopped = true;
  55774. if (stopSubEmitters) {
  55775. this._stopSubEmitters();
  55776. }
  55777. };
  55778. // animation sheet
  55779. /**
  55780. * Remove all active particles
  55781. */
  55782. ParticleSystem.prototype.reset = function () {
  55783. this._stockParticles = [];
  55784. this._particles = [];
  55785. };
  55786. /**
  55787. * @hidden (for internal use only)
  55788. */
  55789. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55790. var offset = index * this._vertexBufferSize;
  55791. this._vertexData[offset++] = particle.position.x;
  55792. this._vertexData[offset++] = particle.position.y;
  55793. this._vertexData[offset++] = particle.position.z;
  55794. this._vertexData[offset++] = particle.color.r;
  55795. this._vertexData[offset++] = particle.color.g;
  55796. this._vertexData[offset++] = particle.color.b;
  55797. this._vertexData[offset++] = particle.color.a;
  55798. this._vertexData[offset++] = particle.angle;
  55799. this._vertexData[offset++] = particle.scale.x * particle.size;
  55800. this._vertexData[offset++] = particle.scale.y * particle.size;
  55801. if (this._isAnimationSheetEnabled) {
  55802. this._vertexData[offset++] = particle.cellIndex;
  55803. }
  55804. if (!this._isBillboardBased) {
  55805. if (particle._initialDirection) {
  55806. this._vertexData[offset++] = particle._initialDirection.x;
  55807. this._vertexData[offset++] = particle._initialDirection.y;
  55808. this._vertexData[offset++] = particle._initialDirection.z;
  55809. }
  55810. else {
  55811. this._vertexData[offset++] = particle.direction.x;
  55812. this._vertexData[offset++] = particle.direction.y;
  55813. this._vertexData[offset++] = particle.direction.z;
  55814. }
  55815. }
  55816. if (!this._useInstancing) {
  55817. if (this._isAnimationSheetEnabled) {
  55818. if (offsetX === 0)
  55819. offsetX = this._epsilon;
  55820. else if (offsetX === 1)
  55821. offsetX = 1 - this._epsilon;
  55822. if (offsetY === 0)
  55823. offsetY = this._epsilon;
  55824. else if (offsetY === 1)
  55825. offsetY = 1 - this._epsilon;
  55826. }
  55827. this._vertexData[offset++] = offsetX;
  55828. this._vertexData[offset++] = offsetY;
  55829. }
  55830. };
  55831. ParticleSystem.prototype._stopSubEmitters = function () {
  55832. if (!this.activeSubSystems) {
  55833. return;
  55834. }
  55835. this.activeSubSystems.forEach(function (subSystem) {
  55836. subSystem.stop(true);
  55837. });
  55838. this.activeSubSystems = new Array();
  55839. };
  55840. ParticleSystem.prototype._removeFromRoot = function () {
  55841. if (!this._rootParticleSystem) {
  55842. return;
  55843. }
  55844. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55845. if (index !== -1) {
  55846. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55847. }
  55848. };
  55849. // End of sub system methods
  55850. ParticleSystem.prototype._update = function (newParticles) {
  55851. // Update current
  55852. this._alive = this._particles.length > 0;
  55853. this.updateFunction(this._particles);
  55854. // Add new ones
  55855. var worldMatrix;
  55856. if (this.emitter.position) {
  55857. var emitterMesh = this.emitter;
  55858. worldMatrix = emitterMesh.getWorldMatrix();
  55859. }
  55860. else {
  55861. var emitterPosition = this.emitter;
  55862. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55863. }
  55864. var particle;
  55865. var _loop_2 = function () {
  55866. if (this_1._particles.length === this_1._capacity) {
  55867. return "break";
  55868. }
  55869. particle = this_1._createParticle();
  55870. this_1._particles.push(particle);
  55871. // Emitter
  55872. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55873. if (this_1.startPositionFunction) {
  55874. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55875. }
  55876. else {
  55877. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55878. }
  55879. if (this_1.startDirectionFunction) {
  55880. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55881. }
  55882. else {
  55883. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55884. }
  55885. if (emitPower === 0) {
  55886. if (!particle._initialDirection) {
  55887. particle._initialDirection = particle.direction.clone();
  55888. }
  55889. else {
  55890. particle._initialDirection.copyFrom(particle.direction);
  55891. }
  55892. }
  55893. else {
  55894. particle._initialDirection = null;
  55895. }
  55896. particle.direction.scaleInPlace(emitPower);
  55897. // Life time
  55898. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55899. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55900. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55901. var factorGradient1 = currentGradient;
  55902. var factorGradient2 = nextGradient;
  55903. var lifeTime1 = factorGradient1.getFactor();
  55904. var lifeTime2 = factorGradient2.getFactor();
  55905. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55906. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55907. });
  55908. }
  55909. else {
  55910. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55911. }
  55912. // Size
  55913. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55914. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55915. }
  55916. else {
  55917. particle._currentSizeGradient = this_1._sizeGradients[0];
  55918. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55919. particle.size = particle._currentSize1;
  55920. if (this_1._sizeGradients.length > 1) {
  55921. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55922. }
  55923. else {
  55924. particle._currentSize2 = particle._currentSize1;
  55925. }
  55926. }
  55927. // Size and scale
  55928. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55929. // Angle
  55930. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55931. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55932. }
  55933. else {
  55934. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55935. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55936. particle._currentAngularSpeed1 = particle.angularSpeed;
  55937. if (this_1._angularSpeedGradients.length > 1) {
  55938. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55939. }
  55940. else {
  55941. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55942. }
  55943. }
  55944. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55945. // Velocity
  55946. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55947. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55948. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55949. if (this_1._velocityGradients.length > 1) {
  55950. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55951. }
  55952. else {
  55953. particle._currentVelocity2 = particle._currentVelocity1;
  55954. }
  55955. }
  55956. // Color
  55957. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55958. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55959. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55960. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55961. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55962. }
  55963. else {
  55964. particle._currentColorGradient = this_1._colorGradients[0];
  55965. particle._currentColorGradient.getColorToRef(particle.color);
  55966. particle._currentColor1.copyFrom(particle.color);
  55967. if (this_1._colorGradients.length > 1) {
  55968. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55969. }
  55970. else {
  55971. particle._currentColor2.copyFrom(particle.color);
  55972. }
  55973. }
  55974. // Sheet
  55975. if (this_1._isAnimationSheetEnabled) {
  55976. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55977. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55978. }
  55979. };
  55980. var this_1 = this, step;
  55981. for (var index = 0; index < newParticles; index++) {
  55982. var state_1 = _loop_2();
  55983. if (state_1 === "break")
  55984. break;
  55985. }
  55986. };
  55987. /** @hidden */
  55988. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55989. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55990. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55991. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55992. if (isAnimationSheetEnabled) {
  55993. attributeNamesOrOptions.push("cellIndex");
  55994. }
  55995. if (!isBillboardBased) {
  55996. attributeNamesOrOptions.push("direction");
  55997. }
  55998. return attributeNamesOrOptions;
  55999. };
  56000. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56001. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56002. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  56003. if (isAnimationSheetEnabled) {
  56004. effectCreationOption.push("particlesInfos");
  56005. }
  56006. return effectCreationOption;
  56007. };
  56008. ParticleSystem.prototype._getEffect = function () {
  56009. if (this._customEffect) {
  56010. return this._customEffect;
  56011. }
  56012. ;
  56013. var defines = [];
  56014. if (this._scene.clipPlane) {
  56015. defines.push("#define CLIPPLANE");
  56016. }
  56017. if (this._isAnimationSheetEnabled) {
  56018. defines.push("#define ANIMATESHEET");
  56019. }
  56020. if (this._isBillboardBased) {
  56021. defines.push("#define BILLBOARD");
  56022. switch (this.billboardMode) {
  56023. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56024. defines.push("#define BILLBOARDY");
  56025. break;
  56026. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56027. default:
  56028. break;
  56029. }
  56030. }
  56031. // Effect
  56032. var join = defines.join("\n");
  56033. if (this._cachedDefines !== join) {
  56034. this._cachedDefines = join;
  56035. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56036. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56037. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56038. }
  56039. return this._effect;
  56040. };
  56041. /**
  56042. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56043. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56044. */
  56045. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56046. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56047. if (!this._started)
  56048. return;
  56049. if (!preWarmOnly) {
  56050. var effect = this._getEffect();
  56051. // Check
  56052. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56053. return;
  56054. if (this._currentRenderId === this._scene.getRenderId()) {
  56055. return;
  56056. }
  56057. this._currentRenderId = this._scene.getRenderId();
  56058. }
  56059. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56060. // determine the number of particles we need to create
  56061. var newParticles;
  56062. if (this.manualEmitCount > -1) {
  56063. newParticles = this.manualEmitCount;
  56064. this._newPartsExcess = 0;
  56065. this.manualEmitCount = 0;
  56066. }
  56067. else {
  56068. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56069. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56070. }
  56071. if (this._newPartsExcess > 1.0) {
  56072. newParticles += this._newPartsExcess >> 0;
  56073. this._newPartsExcess -= this._newPartsExcess >> 0;
  56074. }
  56075. this._alive = false;
  56076. if (!this._stopped) {
  56077. this._actualFrame += this._scaledUpdateSpeed;
  56078. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56079. this.stop();
  56080. }
  56081. else {
  56082. newParticles = 0;
  56083. }
  56084. this._update(newParticles);
  56085. // Stopped?
  56086. if (this._stopped) {
  56087. if (!this._alive) {
  56088. this._started = false;
  56089. if (this.onAnimationEnd) {
  56090. this.onAnimationEnd();
  56091. }
  56092. if (this.disposeOnStop) {
  56093. this._scene._toBeDisposed.push(this);
  56094. }
  56095. }
  56096. }
  56097. if (!preWarmOnly) {
  56098. // Update VBO
  56099. var offset = 0;
  56100. for (var index = 0; index < this._particles.length; index++) {
  56101. var particle = this._particles[index];
  56102. this._appendParticleVertices(offset, particle);
  56103. offset += this._useInstancing ? 1 : 4;
  56104. }
  56105. if (this._vertexBuffer) {
  56106. this._vertexBuffer.update(this._vertexData);
  56107. }
  56108. }
  56109. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56110. this.stop();
  56111. }
  56112. };
  56113. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56114. this._appendParticleVertex(offset++, particle, 0, 0);
  56115. if (!this._useInstancing) {
  56116. this._appendParticleVertex(offset++, particle, 1, 0);
  56117. this._appendParticleVertex(offset++, particle, 1, 1);
  56118. this._appendParticleVertex(offset++, particle, 0, 1);
  56119. }
  56120. };
  56121. /**
  56122. * Rebuilds the particle system.
  56123. */
  56124. ParticleSystem.prototype.rebuild = function () {
  56125. this._createIndexBuffer();
  56126. if (this._vertexBuffer) {
  56127. this._vertexBuffer._rebuild();
  56128. }
  56129. };
  56130. /**
  56131. * Is this system ready to be used/rendered
  56132. * @return true if the system is ready
  56133. */
  56134. ParticleSystem.prototype.isReady = function () {
  56135. var effect = this._getEffect();
  56136. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56137. return false;
  56138. }
  56139. return true;
  56140. };
  56141. /**
  56142. * Renders the particle system in its current state.
  56143. * @returns the current number of particles
  56144. */
  56145. ParticleSystem.prototype.render = function () {
  56146. var effect = this._getEffect();
  56147. // Check
  56148. if (!this.isReady() || !this._particles.length) {
  56149. return 0;
  56150. }
  56151. var engine = this._scene.getEngine();
  56152. // Render
  56153. engine.enableEffect(effect);
  56154. engine.setState(false);
  56155. var viewMatrix = this._scene.getViewMatrix();
  56156. effect.setTexture("diffuseSampler", this.particleTexture);
  56157. effect.setMatrix("view", viewMatrix);
  56158. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56159. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56160. var baseSize = this.particleTexture.getBaseSize();
  56161. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56162. }
  56163. effect.setVector2("translationPivot", this.translationPivot);
  56164. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56165. if (this._isBillboardBased) {
  56166. var camera = this._scene.activeCamera;
  56167. effect.setVector3("eyePosition", camera.globalPosition);
  56168. }
  56169. if (this._scene.clipPlane) {
  56170. var clipPlane = this._scene.clipPlane;
  56171. var invView = viewMatrix.clone();
  56172. invView.invert();
  56173. effect.setMatrix("invView", invView);
  56174. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56175. }
  56176. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56177. // Draw order
  56178. switch (this.blendMode) {
  56179. case ParticleSystem.BLENDMODE_ADD:
  56180. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56181. break;
  56182. case ParticleSystem.BLENDMODE_ONEONE:
  56183. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56184. break;
  56185. case ParticleSystem.BLENDMODE_STANDARD:
  56186. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56187. break;
  56188. }
  56189. if (this.forceDepthWrite) {
  56190. engine.setDepthWrite(true);
  56191. }
  56192. if (this._useInstancing) {
  56193. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56194. engine.unbindInstanceAttributes();
  56195. }
  56196. else {
  56197. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56198. }
  56199. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56200. return this._particles.length;
  56201. };
  56202. /**
  56203. * Disposes the particle system and free the associated resources
  56204. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56205. */
  56206. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56207. if (disposeTexture === void 0) { disposeTexture = true; }
  56208. if (this._vertexBuffer) {
  56209. this._vertexBuffer.dispose();
  56210. this._vertexBuffer = null;
  56211. }
  56212. if (this._spriteBuffer) {
  56213. this._spriteBuffer.dispose();
  56214. this._spriteBuffer = null;
  56215. }
  56216. if (this._indexBuffer) {
  56217. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56218. this._indexBuffer = null;
  56219. }
  56220. if (disposeTexture && this.particleTexture) {
  56221. this.particleTexture.dispose();
  56222. this.particleTexture = null;
  56223. }
  56224. this._removeFromRoot();
  56225. // Remove from scene
  56226. var index = this._scene.particleSystems.indexOf(this);
  56227. if (index > -1) {
  56228. this._scene.particleSystems.splice(index, 1);
  56229. }
  56230. // Callback
  56231. this.onDisposeObservable.notifyObservers(this);
  56232. this.onDisposeObservable.clear();
  56233. };
  56234. /**
  56235. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56236. * @param radius The radius of the sphere to emit from
  56237. * @returns the emitter
  56238. */
  56239. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56240. if (radius === void 0) { radius = 1; }
  56241. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56242. this.particleEmitterType = particleEmitter;
  56243. return particleEmitter;
  56244. };
  56245. /**
  56246. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56247. * @param radius The radius of the sphere to emit from
  56248. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56249. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56250. * @returns the emitter
  56251. */
  56252. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56253. if (radius === void 0) { radius = 1; }
  56254. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56255. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56256. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56257. this.particleEmitterType = particleEmitter;
  56258. return particleEmitter;
  56259. };
  56260. /**
  56261. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56262. * @param radius The radius of the cone to emit from
  56263. * @param angle The base angle of the cone
  56264. * @returns the emitter
  56265. */
  56266. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56267. if (radius === void 0) { radius = 1; }
  56268. if (angle === void 0) { angle = Math.PI / 4; }
  56269. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56270. this.particleEmitterType = particleEmitter;
  56271. return particleEmitter;
  56272. };
  56273. // 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.
  56274. /**
  56275. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56276. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56277. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56278. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56279. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56280. * @returns the emitter
  56281. */
  56282. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56283. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56284. this.particleEmitterType = particleEmitter;
  56285. this.direction1 = direction1;
  56286. this.direction2 = direction2;
  56287. this.minEmitBox = minEmitBox;
  56288. this.maxEmitBox = maxEmitBox;
  56289. return particleEmitter;
  56290. };
  56291. // Clone
  56292. /**
  56293. * Clones the particle system.
  56294. * @param name The name of the cloned object
  56295. * @param newEmitter The new emitter to use
  56296. * @returns the cloned particle system
  56297. */
  56298. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56299. var custom = null;
  56300. var program = null;
  56301. if (this.customShader != null) {
  56302. program = this.customShader;
  56303. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56304. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56305. }
  56306. else if (this._customEffect) {
  56307. custom = this._customEffect;
  56308. }
  56309. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56310. result.customShader = program;
  56311. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56312. if (newEmitter === undefined) {
  56313. newEmitter = this.emitter;
  56314. }
  56315. result.emitter = newEmitter;
  56316. if (this.particleTexture) {
  56317. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56318. }
  56319. if (!this.preventAutoStart) {
  56320. result.start();
  56321. }
  56322. return result;
  56323. };
  56324. /**
  56325. * Serializes the particle system to a JSON object.
  56326. * @returns the JSON object
  56327. */
  56328. ParticleSystem.prototype.serialize = function () {
  56329. var serializationObject = {};
  56330. ParticleSystem._Serialize(serializationObject, this);
  56331. serializationObject.textureMask = this.textureMask.asArray();
  56332. serializationObject.customShader = this.customShader;
  56333. serializationObject.preventAutoStart = this.preventAutoStart;
  56334. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56335. return serializationObject;
  56336. };
  56337. /** @hidden */
  56338. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56339. serializationObject.name = particleSystem.name;
  56340. serializationObject.id = particleSystem.id;
  56341. serializationObject.capacity = particleSystem.getCapacity();
  56342. // Emitter
  56343. if (particleSystem.emitter.position) {
  56344. var emitterMesh = particleSystem.emitter;
  56345. serializationObject.emitterId = emitterMesh.id;
  56346. }
  56347. else {
  56348. var emitterPosition = particleSystem.emitter;
  56349. serializationObject.emitter = emitterPosition.asArray();
  56350. }
  56351. // Emitter
  56352. if (particleSystem.particleEmitterType) {
  56353. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56354. }
  56355. if (particleSystem.particleTexture) {
  56356. serializationObject.textureName = particleSystem.particleTexture.name;
  56357. }
  56358. // Animations
  56359. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56360. // Particle system
  56361. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56362. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56363. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56364. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56365. serializationObject.minSize = particleSystem.minSize;
  56366. serializationObject.maxSize = particleSystem.maxSize;
  56367. serializationObject.minScaleX = particleSystem.minScaleX;
  56368. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56369. serializationObject.minScaleY = particleSystem.minScaleY;
  56370. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56371. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56372. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56373. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56374. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56375. serializationObject.emitRate = particleSystem.emitRate;
  56376. serializationObject.gravity = particleSystem.gravity.asArray();
  56377. serializationObject.color1 = particleSystem.color1.asArray();
  56378. serializationObject.color2 = particleSystem.color2.asArray();
  56379. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56380. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56381. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56382. serializationObject.blendMode = particleSystem.blendMode;
  56383. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56384. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56385. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56386. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56387. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56388. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56389. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56390. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56391. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56392. var colorGradients = particleSystem.getColorGradients();
  56393. if (colorGradients) {
  56394. serializationObject.colorGradients = [];
  56395. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56396. var colorGradient = colorGradients_1[_i];
  56397. var serializedGradient = {
  56398. gradient: colorGradient.gradient,
  56399. color1: colorGradient.color1.asArray()
  56400. };
  56401. if (colorGradient.color2) {
  56402. serializedGradient.color2 = colorGradient.color2.asArray();
  56403. }
  56404. serializationObject.colorGradients.push(serializedGradient);
  56405. }
  56406. }
  56407. var sizeGradients = particleSystem.getSizeGradients();
  56408. if (sizeGradients) {
  56409. serializationObject.sizeGradients = [];
  56410. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56411. var sizeGradient = sizeGradients_1[_a];
  56412. var serializedGradient = {
  56413. gradient: sizeGradient.gradient,
  56414. factor1: sizeGradient.factor1
  56415. };
  56416. if (sizeGradient.factor2 !== undefined) {
  56417. serializedGradient.factor2 = sizeGradient.factor2;
  56418. }
  56419. serializationObject.sizeGradients.push(serializedGradient);
  56420. }
  56421. }
  56422. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56423. if (angularSpeedGradients) {
  56424. serializationObject.angularSpeedGradients = [];
  56425. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56426. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56427. var serializedGradient = {
  56428. gradient: angularSpeedGradient.gradient,
  56429. factor1: angularSpeedGradient.factor1
  56430. };
  56431. if (angularSpeedGradient.factor2 !== undefined) {
  56432. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56433. }
  56434. serializationObject.angularSpeedGradients.push(serializedGradient);
  56435. }
  56436. }
  56437. var velocityGradients = particleSystem.getVelocityGradients();
  56438. if (velocityGradients) {
  56439. serializationObject.velocityGradients = [];
  56440. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56441. var velocityGradient = velocityGradients_1[_c];
  56442. var serializedGradient = {
  56443. gradient: velocityGradient.gradient,
  56444. factor1: velocityGradient.factor1
  56445. };
  56446. if (velocityGradient.factor2 !== undefined) {
  56447. serializedGradient.factor2 = velocityGradient.factor2;
  56448. }
  56449. serializationObject.velocityGradients.push(serializedGradient);
  56450. }
  56451. }
  56452. };
  56453. /** @hidden */
  56454. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56455. // Texture
  56456. if (parsedParticleSystem.textureName) {
  56457. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56458. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56459. }
  56460. // Emitter
  56461. if (parsedParticleSystem.emitterId === undefined) {
  56462. particleSystem.emitter = BABYLON.Vector3.Zero();
  56463. }
  56464. else if (parsedParticleSystem.emitterId) {
  56465. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56466. }
  56467. else {
  56468. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56469. }
  56470. // Misc.
  56471. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56472. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56473. }
  56474. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56475. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56476. }
  56477. // Animations
  56478. if (parsedParticleSystem.animations) {
  56479. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56480. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56481. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56482. }
  56483. }
  56484. if (parsedParticleSystem.autoAnimate) {
  56485. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56486. }
  56487. // Particle system
  56488. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56489. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56490. particleSystem.minSize = parsedParticleSystem.minSize;
  56491. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56492. if (parsedParticleSystem.minScaleX) {
  56493. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56494. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56495. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56496. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56497. }
  56498. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56499. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56500. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56501. }
  56502. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56503. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56504. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56505. }
  56506. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56507. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56508. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56509. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56510. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56511. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56512. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56513. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56514. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56515. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56516. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56517. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56518. if (parsedParticleSystem.colorGradients) {
  56519. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56520. var colorGradient = _a[_i];
  56521. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56522. }
  56523. }
  56524. if (parsedParticleSystem.sizeGradients) {
  56525. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56526. var sizeGradient = _c[_b];
  56527. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56528. }
  56529. }
  56530. if (parsedParticleSystem.angularSpeedGradients) {
  56531. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56532. var angularSpeedGradient = _e[_d];
  56533. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56534. }
  56535. }
  56536. if (parsedParticleSystem.velocityGradients) {
  56537. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56538. var velocityGradient = _g[_f];
  56539. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56540. }
  56541. }
  56542. // Emitter
  56543. var emitterType;
  56544. if (parsedParticleSystem.particleEmitterType) {
  56545. switch (parsedParticleSystem.particleEmitterType.type) {
  56546. case "SphereParticleEmitter":
  56547. emitterType = new BABYLON.SphereParticleEmitter();
  56548. break;
  56549. case "SphereDirectedParticleEmitter":
  56550. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56551. break;
  56552. case "ConeEmitter":
  56553. case "ConeParticleEmitter":
  56554. emitterType = new BABYLON.ConeParticleEmitter();
  56555. break;
  56556. case "BoxEmitter":
  56557. case "BoxParticleEmitter":
  56558. default:
  56559. emitterType = new BABYLON.BoxParticleEmitter();
  56560. break;
  56561. }
  56562. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56563. }
  56564. else {
  56565. emitterType = new BABYLON.BoxParticleEmitter();
  56566. emitterType.parse(parsedParticleSystem);
  56567. }
  56568. particleSystem.particleEmitterType = emitterType;
  56569. // Animation sheet
  56570. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56571. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56572. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56573. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56574. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56575. };
  56576. /**
  56577. * Parses a JSON object to create a particle system.
  56578. * @param parsedParticleSystem The JSON object to parse
  56579. * @param scene The scene to create the particle system in
  56580. * @param rootUrl The root url to use to load external dependencies like texture
  56581. * @returns the Parsed particle system
  56582. */
  56583. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56584. var name = parsedParticleSystem.name;
  56585. var custom = null;
  56586. var program = null;
  56587. if (parsedParticleSystem.customShader) {
  56588. program = parsedParticleSystem.customShader;
  56589. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56590. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56591. }
  56592. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56593. particleSystem.customShader = program;
  56594. if (parsedParticleSystem.id) {
  56595. particleSystem.id = parsedParticleSystem.id;
  56596. }
  56597. // Auto start
  56598. if (parsedParticleSystem.preventAutoStart) {
  56599. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56600. }
  56601. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56602. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56603. if (!particleSystem.preventAutoStart) {
  56604. particleSystem.start();
  56605. }
  56606. return particleSystem;
  56607. };
  56608. /**
  56609. * Source color is added to the destination color without alpha affecting the result.
  56610. */
  56611. ParticleSystem.BLENDMODE_ONEONE = 0;
  56612. /**
  56613. * Blend current color and particle color using particle’s alpha.
  56614. */
  56615. ParticleSystem.BLENDMODE_STANDARD = 1;
  56616. /**
  56617. * Add current color and particle color multiplied by particle’s alpha.
  56618. */
  56619. ParticleSystem.BLENDMODE_ADD = 2;
  56620. return ParticleSystem;
  56621. }());
  56622. BABYLON.ParticleSystem = ParticleSystem;
  56623. })(BABYLON || (BABYLON = {}));
  56624. //# sourceMappingURL=babylon.particleSystem.js.map
  56625. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56626. var BABYLON;
  56627. (function (BABYLON) {
  56628. /**
  56629. * Particle emitter emitting particles from the inside of a box.
  56630. * It emits the particles randomly between 2 given directions.
  56631. */
  56632. var BoxParticleEmitter = /** @class */ (function () {
  56633. /**
  56634. * Creates a new instance BoxParticleEmitter
  56635. */
  56636. function BoxParticleEmitter() {
  56637. /**
  56638. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56639. */
  56640. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56641. /**
  56642. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56643. */
  56644. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56645. /**
  56646. * 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.
  56647. */
  56648. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56649. /**
  56650. * 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.
  56651. */
  56652. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56653. }
  56654. /**
  56655. * Called by the particle System when the direction is computed for the created particle.
  56656. * @param worldMatrix is the world matrix of the particle system
  56657. * @param directionToUpdate is the direction vector to update with the result
  56658. * @param particle is the particle we are computed the direction for
  56659. */
  56660. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56661. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56662. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56663. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56664. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56665. };
  56666. /**
  56667. * Called by the particle System when the position is computed for the created particle.
  56668. * @param worldMatrix is the world matrix of the particle system
  56669. * @param positionToUpdate is the position vector to update with the result
  56670. * @param particle is the particle we are computed the position for
  56671. */
  56672. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56673. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56674. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56675. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56676. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56677. };
  56678. /**
  56679. * Clones the current emitter and returns a copy of it
  56680. * @returns the new emitter
  56681. */
  56682. BoxParticleEmitter.prototype.clone = function () {
  56683. var newOne = new BoxParticleEmitter();
  56684. BABYLON.Tools.DeepCopy(this, newOne);
  56685. return newOne;
  56686. };
  56687. /**
  56688. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56689. * @param effect defines the update shader
  56690. */
  56691. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56692. effect.setVector3("direction1", this.direction1);
  56693. effect.setVector3("direction2", this.direction2);
  56694. effect.setVector3("minEmitBox", this.minEmitBox);
  56695. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56696. };
  56697. /**
  56698. * Returns a string to use to update the GPU particles update shader
  56699. * @returns a string containng the defines string
  56700. */
  56701. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56702. return "#define BOXEMITTER";
  56703. };
  56704. /**
  56705. * Returns the string "BoxParticleEmitter"
  56706. * @returns a string containing the class name
  56707. */
  56708. BoxParticleEmitter.prototype.getClassName = function () {
  56709. return "BoxParticleEmitter";
  56710. };
  56711. /**
  56712. * Serializes the particle system to a JSON object.
  56713. * @returns the JSON object
  56714. */
  56715. BoxParticleEmitter.prototype.serialize = function () {
  56716. var serializationObject = {};
  56717. serializationObject.type = this.getClassName();
  56718. serializationObject.direction1 = this.direction1.asArray();
  56719. serializationObject.direction2 = this.direction2.asArray();
  56720. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56721. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56722. return serializationObject;
  56723. };
  56724. /**
  56725. * Parse properties from a JSON object
  56726. * @param serializationObject defines the JSON object
  56727. */
  56728. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56729. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56730. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56731. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56732. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56733. };
  56734. return BoxParticleEmitter;
  56735. }());
  56736. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56737. })(BABYLON || (BABYLON = {}));
  56738. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56739. var BABYLON;
  56740. (function (BABYLON) {
  56741. /**
  56742. * Particle emitter emitting particles from the inside of a cone.
  56743. * It emits the particles alongside the cone volume from the base to the particle.
  56744. * The emission direction might be randomized.
  56745. */
  56746. var ConeParticleEmitter = /** @class */ (function () {
  56747. /**
  56748. * Creates a new instance ConeParticleEmitter
  56749. * @param radius the radius of the emission cone (1 by default)
  56750. * @param angles the cone base angle (PI by default)
  56751. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56752. */
  56753. function ConeParticleEmitter(radius, angle,
  56754. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56755. directionRandomizer) {
  56756. if (radius === void 0) { radius = 1; }
  56757. if (angle === void 0) { angle = Math.PI; }
  56758. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56759. this.directionRandomizer = directionRandomizer;
  56760. /**
  56761. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56762. */
  56763. this.radiusRange = 1;
  56764. /**
  56765. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56766. */
  56767. this.heightRange = 1;
  56768. this.angle = angle;
  56769. this.radius = radius;
  56770. }
  56771. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56772. /**
  56773. * Gets or sets the radius of the emission cone
  56774. */
  56775. get: function () {
  56776. return this._radius;
  56777. },
  56778. set: function (value) {
  56779. this._radius = value;
  56780. this._buildHeight();
  56781. },
  56782. enumerable: true,
  56783. configurable: true
  56784. });
  56785. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56786. /**
  56787. * Gets or sets the angle of the emission cone
  56788. */
  56789. get: function () {
  56790. return this._angle;
  56791. },
  56792. set: function (value) {
  56793. this._angle = value;
  56794. this._buildHeight();
  56795. },
  56796. enumerable: true,
  56797. configurable: true
  56798. });
  56799. ConeParticleEmitter.prototype._buildHeight = function () {
  56800. if (this._angle !== 0) {
  56801. this._height = this._radius / Math.tan(this._angle / 2);
  56802. }
  56803. else {
  56804. this._height = 1;
  56805. }
  56806. };
  56807. /**
  56808. * Called by the particle System when the direction is computed for the created particle.
  56809. * @param worldMatrix is the world matrix of the particle system
  56810. * @param directionToUpdate is the direction vector to update with the result
  56811. * @param particle is the particle we are computed the direction for
  56812. */
  56813. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56814. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56815. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56816. }
  56817. else {
  56818. // measure the direction Vector from the emitter to the particle.
  56819. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56820. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56821. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56822. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56823. direction.x += randX;
  56824. direction.y += randY;
  56825. direction.z += randZ;
  56826. direction.normalize();
  56827. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56828. }
  56829. };
  56830. /**
  56831. * Called by the particle System when the position is computed for the created particle.
  56832. * @param worldMatrix is the world matrix of the particle system
  56833. * @param positionToUpdate is the position vector to update with the result
  56834. * @param particle is the particle we are computed the position for
  56835. */
  56836. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56837. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56838. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56839. // Better distribution in a cone at normal angles.
  56840. h = 1 - h * h;
  56841. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56842. radius = radius * h;
  56843. var randX = radius * Math.sin(s);
  56844. var randZ = radius * Math.cos(s);
  56845. var randY = h * this._height;
  56846. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56847. };
  56848. /**
  56849. * Clones the current emitter and returns a copy of it
  56850. * @returns the new emitter
  56851. */
  56852. ConeParticleEmitter.prototype.clone = function () {
  56853. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56854. BABYLON.Tools.DeepCopy(this, newOne);
  56855. return newOne;
  56856. };
  56857. /**
  56858. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56859. * @param effect defines the update shader
  56860. */
  56861. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56862. effect.setFloat2("radius", this._radius, this.radiusRange);
  56863. effect.setFloat("coneAngle", this._angle);
  56864. effect.setFloat2("height", this._height, this.heightRange);
  56865. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56866. };
  56867. /**
  56868. * Returns a string to use to update the GPU particles update shader
  56869. * @returns a string containng the defines string
  56870. */
  56871. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56872. return "#define CONEEMITTER";
  56873. };
  56874. /**
  56875. * Returns the string "ConeParticleEmitter"
  56876. * @returns a string containing the class name
  56877. */
  56878. ConeParticleEmitter.prototype.getClassName = function () {
  56879. return "ConeParticleEmitter";
  56880. };
  56881. /**
  56882. * Serializes the particle system to a JSON object.
  56883. * @returns the JSON object
  56884. */
  56885. ConeParticleEmitter.prototype.serialize = function () {
  56886. var serializationObject = {};
  56887. serializationObject.type = this.getClassName();
  56888. serializationObject.radius = this._radius;
  56889. serializationObject.angle = this._angle;
  56890. serializationObject.directionRandomizer = this.directionRandomizer;
  56891. return serializationObject;
  56892. };
  56893. /**
  56894. * Parse properties from a JSON object
  56895. * @param serializationObject defines the JSON object
  56896. */
  56897. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56898. this.radius = serializationObject.radius;
  56899. this.angle = serializationObject.angle;
  56900. this.directionRandomizer = serializationObject.directionRandomizer;
  56901. };
  56902. return ConeParticleEmitter;
  56903. }());
  56904. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56905. })(BABYLON || (BABYLON = {}));
  56906. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56907. var BABYLON;
  56908. (function (BABYLON) {
  56909. /**
  56910. * Particle emitter emitting particles from the inside of a sphere.
  56911. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56912. */
  56913. var SphereParticleEmitter = /** @class */ (function () {
  56914. /**
  56915. * Creates a new instance SphereParticleEmitter
  56916. * @param radius the radius of the emission sphere (1 by default)
  56917. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56918. */
  56919. function SphereParticleEmitter(
  56920. /**
  56921. * The radius of the emission sphere.
  56922. */
  56923. radius,
  56924. /**
  56925. * How much to randomize the particle direction [0-1].
  56926. */
  56927. directionRandomizer) {
  56928. if (radius === void 0) { radius = 1; }
  56929. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56930. this.radius = radius;
  56931. this.directionRandomizer = directionRandomizer;
  56932. /**
  56933. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56934. */
  56935. this.radiusRange = 1;
  56936. }
  56937. /**
  56938. * Called by the particle System when the direction is computed for the created particle.
  56939. * @param worldMatrix is the world matrix of the particle system
  56940. * @param directionToUpdate is the direction vector to update with the result
  56941. * @param particle is the particle we are computed the direction for
  56942. */
  56943. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56944. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56945. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56946. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56947. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56948. direction.x += randX;
  56949. direction.y += randY;
  56950. direction.z += randZ;
  56951. direction.normalize();
  56952. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56953. };
  56954. /**
  56955. * Called by the particle System when the position is computed for the created particle.
  56956. * @param worldMatrix is the world matrix of the particle system
  56957. * @param positionToUpdate is the position vector to update with the result
  56958. * @param particle is the particle we are computed the position for
  56959. */
  56960. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56961. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56962. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56963. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56964. var theta = Math.acos(2 * v - 1);
  56965. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56966. var randY = randRadius * Math.cos(theta);
  56967. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56968. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56969. };
  56970. /**
  56971. * Clones the current emitter and returns a copy of it
  56972. * @returns the new emitter
  56973. */
  56974. SphereParticleEmitter.prototype.clone = function () {
  56975. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56976. BABYLON.Tools.DeepCopy(this, newOne);
  56977. return newOne;
  56978. };
  56979. /**
  56980. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56981. * @param effect defines the update shader
  56982. */
  56983. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56984. effect.setFloat("radius", this.radius);
  56985. effect.setFloat("radiusRange", this.radiusRange);
  56986. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56987. };
  56988. /**
  56989. * Returns a string to use to update the GPU particles update shader
  56990. * @returns a string containng the defines string
  56991. */
  56992. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56993. return "#define SPHEREEMITTER";
  56994. };
  56995. /**
  56996. * Returns the string "SphereParticleEmitter"
  56997. * @returns a string containing the class name
  56998. */
  56999. SphereParticleEmitter.prototype.getClassName = function () {
  57000. return "SphereParticleEmitter";
  57001. };
  57002. /**
  57003. * Serializes the particle system to a JSON object.
  57004. * @returns the JSON object
  57005. */
  57006. SphereParticleEmitter.prototype.serialize = function () {
  57007. var serializationObject = {};
  57008. serializationObject.type = this.getClassName();
  57009. serializationObject.radius = this.radius;
  57010. serializationObject.radiusRange = this.radiusRange;
  57011. serializationObject.directionRandomizer = this.directionRandomizer;
  57012. return serializationObject;
  57013. };
  57014. /**
  57015. * Parse properties from a JSON object
  57016. * @param serializationObject defines the JSON object
  57017. */
  57018. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57019. this.radius = serializationObject.radius;
  57020. this.radiusRange = serializationObject.radiusRange;
  57021. this.directionRandomizer = serializationObject.directionRandomizer;
  57022. };
  57023. return SphereParticleEmitter;
  57024. }());
  57025. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57026. /**
  57027. * Particle emitter emitting particles from the inside of a sphere.
  57028. * It emits the particles randomly between two vectors.
  57029. */
  57030. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57031. __extends(SphereDirectedParticleEmitter, _super);
  57032. /**
  57033. * Creates a new instance SphereDirectedParticleEmitter
  57034. * @param radius the radius of the emission sphere (1 by default)
  57035. * @param direction1 the min limit of the emission direction (up vector by default)
  57036. * @param direction2 the max limit of the emission direction (up vector by default)
  57037. */
  57038. function SphereDirectedParticleEmitter(radius,
  57039. /**
  57040. * The min limit of the emission direction.
  57041. */
  57042. direction1,
  57043. /**
  57044. * The max limit of the emission direction.
  57045. */
  57046. direction2) {
  57047. if (radius === void 0) { radius = 1; }
  57048. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57049. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57050. var _this = _super.call(this, radius) || this;
  57051. _this.direction1 = direction1;
  57052. _this.direction2 = direction2;
  57053. return _this;
  57054. }
  57055. /**
  57056. * Called by the particle System when the direction is computed for the created particle.
  57057. * @param worldMatrix is the world matrix of the particle system
  57058. * @param directionToUpdate is the direction vector to update with the result
  57059. * @param particle is the particle we are computed the direction for
  57060. */
  57061. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57062. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57063. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57064. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57065. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57066. };
  57067. /**
  57068. * Clones the current emitter and returns a copy of it
  57069. * @returns the new emitter
  57070. */
  57071. SphereDirectedParticleEmitter.prototype.clone = function () {
  57072. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57073. BABYLON.Tools.DeepCopy(this, newOne);
  57074. return newOne;
  57075. };
  57076. /**
  57077. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57078. * @param effect defines the update shader
  57079. */
  57080. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57081. effect.setFloat("radius", this.radius);
  57082. effect.setFloat("radiusRange", this.radiusRange);
  57083. effect.setVector3("direction1", this.direction1);
  57084. effect.setVector3("direction2", this.direction2);
  57085. };
  57086. /**
  57087. * Returns a string to use to update the GPU particles update shader
  57088. * @returns a string containng the defines string
  57089. */
  57090. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57091. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57092. };
  57093. /**
  57094. * Returns the string "SphereDirectedParticleEmitter"
  57095. * @returns a string containing the class name
  57096. */
  57097. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57098. return "SphereDirectedParticleEmitter";
  57099. };
  57100. /**
  57101. * Serializes the particle system to a JSON object.
  57102. * @returns the JSON object
  57103. */
  57104. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57105. var serializationObject = _super.prototype.serialize.call(this);
  57106. serializationObject.direction1 = this.direction1.asArray();
  57107. serializationObject.direction2 = this.direction2.asArray();
  57108. return serializationObject;
  57109. };
  57110. /**
  57111. * Parse properties from a JSON object
  57112. * @param serializationObject defines the JSON object
  57113. */
  57114. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57115. _super.prototype.parse.call(this, serializationObject);
  57116. this.direction1.copyFrom(serializationObject.direction1);
  57117. this.direction2.copyFrom(serializationObject.direction2);
  57118. };
  57119. return SphereDirectedParticleEmitter;
  57120. }(SphereParticleEmitter));
  57121. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57122. })(BABYLON || (BABYLON = {}));
  57123. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57124. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57125. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57126. s = arguments[i];
  57127. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57128. t[p] = s[p];
  57129. }
  57130. return t;
  57131. };
  57132. var BABYLON;
  57133. (function (BABYLON) {
  57134. /**
  57135. * This represents a GPU particle system in Babylon
  57136. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57137. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57138. */
  57139. var GPUParticleSystem = /** @class */ (function () {
  57140. /**
  57141. * Instantiates a GPU particle system.
  57142. * 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.
  57143. * @param name The name of the particle system
  57144. * @param options The options used to create the system
  57145. * @param scene The scene the particle system belongs to
  57146. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57147. */
  57148. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  57149. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57150. /**
  57151. * The emitter represents the Mesh or position we are attaching the particle system to.
  57152. */
  57153. this.emitter = null;
  57154. /**
  57155. * The rendering group used by the Particle system to chose when to render.
  57156. */
  57157. this.renderingGroupId = 0;
  57158. /**
  57159. * The layer mask we are rendering the particles through.
  57160. */
  57161. this.layerMask = 0x0FFFFFFF;
  57162. this._accumulatedCount = 0;
  57163. this._targetIndex = 0;
  57164. this._currentRenderId = -1;
  57165. this._started = false;
  57166. this._stopped = false;
  57167. this._timeDelta = 0;
  57168. this._attributesStrideSize = 21;
  57169. this._actualFrame = 0;
  57170. this._rawTextureWidth = 256;
  57171. /**
  57172. * List of animations used by the particle system.
  57173. */
  57174. this.animations = [];
  57175. /**
  57176. * An event triggered when the system is disposed.
  57177. */
  57178. this.onDisposeObservable = new BABYLON.Observable();
  57179. /**
  57180. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57181. */
  57182. this.updateSpeed = 0.01;
  57183. /**
  57184. * The amount of time the particle system is running (depends of the overall update speed).
  57185. */
  57186. this.targetStopDuration = 0;
  57187. /**
  57188. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57189. */
  57190. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57191. /**
  57192. * Minimum life time of emitting particles.
  57193. */
  57194. this.minLifeTime = 1;
  57195. /**
  57196. * Maximum life time of emitting particles.
  57197. */
  57198. this.maxLifeTime = 1;
  57199. /**
  57200. * Minimum Size of emitting particles.
  57201. */
  57202. this.minSize = 1;
  57203. /**
  57204. * Maximum Size of emitting particles.
  57205. */
  57206. this.maxSize = 1;
  57207. /**
  57208. * Minimum scale of emitting particles on X axis.
  57209. */
  57210. this.minScaleX = 1;
  57211. /**
  57212. * Maximum scale of emitting particles on X axis.
  57213. */
  57214. this.maxScaleX = 1;
  57215. /**
  57216. * Minimum scale of emitting particles on Y axis.
  57217. */
  57218. this.minScaleY = 1;
  57219. /**
  57220. * Maximum scale of emitting particles on Y axis.
  57221. */
  57222. this.maxScaleY = 1;
  57223. /**
  57224. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57225. */
  57226. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57227. /**
  57228. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57229. */
  57230. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57231. /**
  57232. * Color the particle will have at the end of its lifetime.
  57233. */
  57234. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57235. /**
  57236. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57237. */
  57238. this.emitRate = 100;
  57239. /**
  57240. * You can use gravity if you want to give an orientation to your particles.
  57241. */
  57242. this.gravity = BABYLON.Vector3.Zero();
  57243. /**
  57244. * Minimum power of emitting particles.
  57245. */
  57246. this.minEmitPower = 1;
  57247. /**
  57248. * Maximum power of emitting particles.
  57249. */
  57250. this.maxEmitPower = 1;
  57251. /**
  57252. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57253. */
  57254. this.minAngularSpeed = 0;
  57255. /**
  57256. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57257. */
  57258. this.maxAngularSpeed = 0;
  57259. /**
  57260. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57261. * to override the particles.
  57262. */
  57263. this.forceDepthWrite = false;
  57264. this._preWarmDone = false;
  57265. /** 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 */
  57266. this.preWarmCycles = 0;
  57267. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57268. this.preWarmStepOffset = 1;
  57269. /**
  57270. * Gets or sets the minimal initial rotation in radians.
  57271. */
  57272. this.minInitialRotation = 0;
  57273. /**
  57274. * Gets or sets the maximal initial rotation in radians.
  57275. */
  57276. this.maxInitialRotation = 0;
  57277. /**
  57278. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  57279. */
  57280. this.spriteCellChangeSpeed = 1;
  57281. /**
  57282. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57283. */
  57284. this.startSpriteCellID = 0;
  57285. /**
  57286. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57287. */
  57288. this.endSpriteCellID = 0;
  57289. /**
  57290. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57291. */
  57292. this.spriteCellWidth = 0;
  57293. /**
  57294. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57295. */
  57296. this.spriteCellHeight = 0;
  57297. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57298. this.translationPivot = new BABYLON.Vector2(0, 0);
  57299. /**
  57300. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57301. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57302. */
  57303. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57304. this._isBillboardBased = true;
  57305. this._colorGradients = null;
  57306. this._angularSpeedGradients = null;
  57307. this._sizeGradients = null;
  57308. this._velocityGradients = null;
  57309. this.id = name;
  57310. this.name = name;
  57311. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57312. this._engine = this._scene.getEngine();
  57313. if (!options.randomTextureSize) {
  57314. delete options.randomTextureSize;
  57315. }
  57316. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57317. var optionsAsNumber = options;
  57318. if (isFinite(optionsAsNumber)) {
  57319. fullOptions.capacity = optionsAsNumber;
  57320. }
  57321. this._capacity = fullOptions.capacity;
  57322. this._activeCount = fullOptions.capacity;
  57323. this._currentActiveCount = 0;
  57324. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57325. this._scene.particleSystems.push(this);
  57326. this._updateEffectOptions = {
  57327. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57328. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57329. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57330. "angleRange", "radiusRange", "cellInfos"],
  57331. uniformBuffersNames: [],
  57332. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  57333. defines: "",
  57334. fallbacks: null,
  57335. onCompiled: null,
  57336. onError: null,
  57337. indexParameters: null,
  57338. maxSimultaneousLights: 0,
  57339. transformFeedbackVaryings: []
  57340. };
  57341. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57342. // Random data
  57343. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57344. var d = [];
  57345. for (var i = 0; i < maxTextureSize; ++i) {
  57346. d.push(Math.random());
  57347. d.push(Math.random());
  57348. d.push(Math.random());
  57349. d.push(Math.random());
  57350. }
  57351. 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);
  57352. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57353. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57354. d = [];
  57355. for (var i = 0; i < maxTextureSize; ++i) {
  57356. d.push(Math.random());
  57357. d.push(Math.random());
  57358. d.push(Math.random());
  57359. d.push(Math.random());
  57360. }
  57361. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57362. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57363. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57364. this._randomTextureSize = maxTextureSize;
  57365. }
  57366. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57367. /**
  57368. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57369. */
  57370. get: function () {
  57371. if (!BABYLON.Engine.LastCreatedEngine) {
  57372. return false;
  57373. }
  57374. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57375. },
  57376. enumerable: true,
  57377. configurable: true
  57378. });
  57379. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57380. /**
  57381. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57382. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57383. */
  57384. get: function () {
  57385. if (this.particleEmitterType.direction1) {
  57386. return this.particleEmitterType.direction1;
  57387. }
  57388. return BABYLON.Vector3.Zero();
  57389. },
  57390. set: function (value) {
  57391. if (this.particleEmitterType.direction1) {
  57392. this.particleEmitterType.direction1 = value;
  57393. }
  57394. },
  57395. enumerable: true,
  57396. configurable: true
  57397. });
  57398. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57399. /**
  57400. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57401. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57402. */
  57403. get: function () {
  57404. if (this.particleEmitterType.direction2) {
  57405. return this.particleEmitterType.direction2;
  57406. }
  57407. return BABYLON.Vector3.Zero();
  57408. },
  57409. set: function (value) {
  57410. if (this.particleEmitterType.direction2) {
  57411. this.particleEmitterType.direction2 = value;
  57412. }
  57413. },
  57414. enumerable: true,
  57415. configurable: true
  57416. });
  57417. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57418. /**
  57419. * 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.
  57420. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57421. */
  57422. get: function () {
  57423. if (this.particleEmitterType.minEmitBox) {
  57424. return this.particleEmitterType.minEmitBox;
  57425. }
  57426. return BABYLON.Vector3.Zero();
  57427. },
  57428. set: function (value) {
  57429. if (this.particleEmitterType.minEmitBox) {
  57430. this.particleEmitterType.minEmitBox = value;
  57431. }
  57432. },
  57433. enumerable: true,
  57434. configurable: true
  57435. });
  57436. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57437. /**
  57438. * 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.
  57439. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57440. */
  57441. get: function () {
  57442. if (this.particleEmitterType.maxEmitBox) {
  57443. return this.particleEmitterType.maxEmitBox;
  57444. }
  57445. return BABYLON.Vector3.Zero();
  57446. },
  57447. set: function (value) {
  57448. if (this.particleEmitterType.maxEmitBox) {
  57449. this.particleEmitterType.maxEmitBox = value;
  57450. }
  57451. },
  57452. enumerable: true,
  57453. configurable: true
  57454. });
  57455. /**
  57456. * Gets the maximum number of particles active at the same time.
  57457. * @returns The max number of active particles.
  57458. */
  57459. GPUParticleSystem.prototype.getCapacity = function () {
  57460. return this._capacity;
  57461. };
  57462. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57463. /**
  57464. * Gets or set the number of active particles
  57465. */
  57466. get: function () {
  57467. return this._activeCount;
  57468. },
  57469. set: function (value) {
  57470. this._activeCount = Math.min(value, this._capacity);
  57471. },
  57472. enumerable: true,
  57473. configurable: true
  57474. });
  57475. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57476. /**
  57477. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57478. */
  57479. get: function () {
  57480. return this._isAnimationSheetEnabled;
  57481. },
  57482. enumerable: true,
  57483. configurable: true
  57484. });
  57485. /**
  57486. * Is this system ready to be used/rendered
  57487. * @return true if the system is ready
  57488. */
  57489. GPUParticleSystem.prototype.isReady = function () {
  57490. if (!this._updateEffect) {
  57491. this._recreateUpdateEffect();
  57492. this._recreateRenderEffect();
  57493. return false;
  57494. }
  57495. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57496. return false;
  57497. }
  57498. return true;
  57499. };
  57500. /**
  57501. * Gets Wether the system has been started.
  57502. * @returns True if it has been started, otherwise false.
  57503. */
  57504. GPUParticleSystem.prototype.isStarted = function () {
  57505. return this._started;
  57506. };
  57507. /**
  57508. * Starts the particle system and begins to emit.
  57509. */
  57510. GPUParticleSystem.prototype.start = function () {
  57511. this._started = true;
  57512. this._stopped = false;
  57513. this._preWarmDone = false;
  57514. };
  57515. /**
  57516. * Stops the particle system.
  57517. */
  57518. GPUParticleSystem.prototype.stop = function () {
  57519. this._stopped = true;
  57520. };
  57521. /**
  57522. * Remove all active particles
  57523. */
  57524. GPUParticleSystem.prototype.reset = function () {
  57525. this._releaseBuffers();
  57526. this._releaseVAOs();
  57527. this._currentActiveCount = 0;
  57528. this._targetIndex = 0;
  57529. };
  57530. /**
  57531. * Returns the string "GPUParticleSystem"
  57532. * @returns a string containing the class name
  57533. */
  57534. GPUParticleSystem.prototype.getClassName = function () {
  57535. return "GPUParticleSystem";
  57536. };
  57537. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57538. /**
  57539. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57540. */
  57541. get: function () {
  57542. return this._isBillboardBased;
  57543. },
  57544. set: function (value) {
  57545. if (this._isBillboardBased === value) {
  57546. return;
  57547. }
  57548. this._isBillboardBased = value;
  57549. this._releaseBuffers();
  57550. },
  57551. enumerable: true,
  57552. configurable: true
  57553. });
  57554. /**
  57555. * Gets the current list of color gradients.
  57556. * You must use addColorGradient and removeColorGradient to udpate this list
  57557. * @returns the list of color gradients
  57558. */
  57559. GPUParticleSystem.prototype.getColorGradients = function () {
  57560. return this._colorGradients;
  57561. };
  57562. /**
  57563. * Gets the current list of size gradients.
  57564. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57565. * @returns the list of size gradients
  57566. */
  57567. GPUParticleSystem.prototype.getSizeGradients = function () {
  57568. return this._sizeGradients;
  57569. };
  57570. /**
  57571. * Gets the current list of angular speed gradients.
  57572. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57573. * @returns the list of angular speed gradients
  57574. */
  57575. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57576. return this._angularSpeedGradients;
  57577. };
  57578. /**
  57579. * Gets the current list of velocity gradients.
  57580. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57581. * @returns the list of angular speed gradients
  57582. */
  57583. GPUParticleSystem.prototype.getVelocityGradients = function () {
  57584. return this._velocityGradients;
  57585. };
  57586. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57587. if (!gradients) {
  57588. return this;
  57589. }
  57590. var index = 0;
  57591. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57592. var valueGradient = gradients_1[_i];
  57593. if (valueGradient.gradient === gradient) {
  57594. gradients.splice(index, 1);
  57595. break;
  57596. }
  57597. index++;
  57598. }
  57599. if (texture) {
  57600. texture.dispose();
  57601. }
  57602. this._releaseBuffers();
  57603. return this;
  57604. };
  57605. /**
  57606. * Adds a new color gradient
  57607. * @param gradient defines the gradient to use (between 0 and 1)
  57608. * @param color defines the color to affect to the specified gradient
  57609. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57610. * @returns the current particle system
  57611. */
  57612. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57613. if (!this._colorGradients) {
  57614. this._colorGradients = [];
  57615. }
  57616. var colorGradient = new BABYLON.ColorGradient();
  57617. colorGradient.gradient = gradient;
  57618. colorGradient.color1 = color1;
  57619. this._colorGradients.push(colorGradient);
  57620. this._colorGradients.sort(function (a, b) {
  57621. if (a.gradient < b.gradient) {
  57622. return -1;
  57623. }
  57624. else if (a.gradient > b.gradient) {
  57625. return 1;
  57626. }
  57627. return 0;
  57628. });
  57629. if (this._colorGradientsTexture) {
  57630. this._colorGradientsTexture.dispose();
  57631. this._colorGradientsTexture = null;
  57632. }
  57633. this._releaseBuffers();
  57634. return this;
  57635. };
  57636. /**
  57637. * Remove a specific color gradient
  57638. * @param gradient defines the gradient to remove
  57639. * @returns the current particle system
  57640. */
  57641. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57642. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57643. this._colorGradientsTexture = null;
  57644. return this;
  57645. };
  57646. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57647. var valueGradient = new BABYLON.FactorGradient();
  57648. valueGradient.gradient = gradient;
  57649. valueGradient.factor1 = factor;
  57650. factorGradients.push(valueGradient);
  57651. factorGradients.sort(function (a, b) {
  57652. if (a.gradient < b.gradient) {
  57653. return -1;
  57654. }
  57655. else if (a.gradient > b.gradient) {
  57656. return 1;
  57657. }
  57658. return 0;
  57659. });
  57660. this._releaseBuffers();
  57661. };
  57662. /**
  57663. * Adds a new size gradient
  57664. * @param gradient defines the gradient to use (between 0 and 1)
  57665. * @param factor defines the size factor to affect to the specified gradient
  57666. * @returns the current particle system
  57667. */
  57668. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57669. if (!this._sizeGradients) {
  57670. this._sizeGradients = [];
  57671. }
  57672. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57673. if (this._sizeGradientsTexture) {
  57674. this._sizeGradientsTexture.dispose();
  57675. this._sizeGradientsTexture = null;
  57676. }
  57677. this._releaseBuffers();
  57678. return this;
  57679. };
  57680. /**
  57681. * Remove a specific size gradient
  57682. * @param gradient defines the gradient to remove
  57683. * @returns the current particle system
  57684. */
  57685. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57686. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57687. this._sizeGradientsTexture = null;
  57688. return this;
  57689. };
  57690. /**
  57691. * Adds a new angular speed gradient
  57692. * @param gradient defines the gradient to use (between 0 and 1)
  57693. * @param factor defines the size factor to affect to the specified gradient
  57694. * @returns the current particle system
  57695. */
  57696. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57697. if (!this._angularSpeedGradients) {
  57698. this._angularSpeedGradients = [];
  57699. }
  57700. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57701. if (this._angularSpeedGradientsTexture) {
  57702. this._angularSpeedGradientsTexture.dispose();
  57703. this._angularSpeedGradientsTexture = null;
  57704. }
  57705. this._releaseBuffers();
  57706. return this;
  57707. };
  57708. /**
  57709. * Remove a specific angular speed gradient
  57710. * @param gradient defines the gradient to remove
  57711. * @returns the current particle system
  57712. */
  57713. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57714. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57715. this._angularSpeedGradientsTexture = null;
  57716. return this;
  57717. };
  57718. /**
  57719. * Adds a new velocity gradient
  57720. * @param gradient defines the gradient to use (between 0 and 1)
  57721. * @param factor defines the size factor to affect to the specified gradient
  57722. * @returns the current particle system
  57723. */
  57724. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  57725. if (!this._velocityGradients) {
  57726. this._velocityGradients = [];
  57727. }
  57728. this._addFactorGradient(this._velocityGradients, gradient, factor);
  57729. if (this._velocityGradientsTexture) {
  57730. this._velocityGradientsTexture.dispose();
  57731. this._velocityGradientsTexture = null;
  57732. }
  57733. this._releaseBuffers();
  57734. return this;
  57735. };
  57736. /**
  57737. * Remove a specific velocity gradient
  57738. * @param gradient defines the gradient to remove
  57739. * @returns the current particle system
  57740. */
  57741. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57742. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  57743. this._velocityGradientsTexture = null;
  57744. return this;
  57745. };
  57746. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57747. var updateVertexBuffers = {};
  57748. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57749. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57750. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57751. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57752. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57753. var offset = 12;
  57754. if (!this._colorGradientsTexture) {
  57755. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57756. offset += 4;
  57757. }
  57758. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57759. offset += 3;
  57760. if (!this._isBillboardBased) {
  57761. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57762. offset += 3;
  57763. }
  57764. if (this._angularSpeedGradientsTexture) {
  57765. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57766. offset += 1;
  57767. }
  57768. else {
  57769. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57770. offset += 2;
  57771. }
  57772. if (this._isAnimationSheetEnabled) {
  57773. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57774. offset += 1;
  57775. }
  57776. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57777. this._engine.bindArrayBuffer(null);
  57778. return vao;
  57779. };
  57780. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57781. var renderVertexBuffers = {};
  57782. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57783. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57784. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57785. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57786. var offset = 12;
  57787. if (!this._colorGradientsTexture) {
  57788. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57789. offset += 4;
  57790. }
  57791. offset += 3; // Direction
  57792. if (!this._isBillboardBased) {
  57793. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57794. offset += 3;
  57795. }
  57796. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57797. if (this._angularSpeedGradientsTexture) {
  57798. offset++;
  57799. }
  57800. else {
  57801. offset += 2;
  57802. }
  57803. if (this._isAnimationSheetEnabled) {
  57804. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57805. offset += 1;
  57806. }
  57807. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57808. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57809. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57810. this._engine.bindArrayBuffer(null);
  57811. return vao;
  57812. };
  57813. GPUParticleSystem.prototype._initialize = function (force) {
  57814. if (force === void 0) { force = false; }
  57815. if (this._buffer0 && !force) {
  57816. return;
  57817. }
  57818. var engine = this._scene.getEngine();
  57819. var data = new Array();
  57820. if (!this.isBillboardBased) {
  57821. this._attributesStrideSize += 3;
  57822. }
  57823. if (this._colorGradientsTexture) {
  57824. this._attributesStrideSize -= 4;
  57825. }
  57826. if (this._angularSpeedGradientsTexture) {
  57827. this._attributesStrideSize -= 1;
  57828. }
  57829. if (this._isAnimationSheetEnabled) {
  57830. this._attributesStrideSize += 1;
  57831. }
  57832. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57833. // position
  57834. data.push(0.0);
  57835. data.push(0.0);
  57836. data.push(0.0);
  57837. // Age and life
  57838. data.push(0.0); // create the particle as a dead one to create a new one at start
  57839. data.push(0.0);
  57840. // Seed
  57841. data.push(Math.random());
  57842. data.push(Math.random());
  57843. data.push(Math.random());
  57844. data.push(Math.random());
  57845. // Size
  57846. data.push(0.0);
  57847. data.push(0.0);
  57848. data.push(0.0);
  57849. if (!this._colorGradientsTexture) {
  57850. // color
  57851. data.push(0.0);
  57852. data.push(0.0);
  57853. data.push(0.0);
  57854. data.push(0.0);
  57855. }
  57856. // direction
  57857. data.push(0.0);
  57858. data.push(0.0);
  57859. data.push(0.0);
  57860. if (!this.isBillboardBased) {
  57861. // initialDirection
  57862. data.push(0.0);
  57863. data.push(0.0);
  57864. data.push(0.0);
  57865. }
  57866. // angle
  57867. data.push(0.0);
  57868. if (!this._angularSpeedGradientsTexture) {
  57869. data.push(0.0);
  57870. }
  57871. if (this._isAnimationSheetEnabled) {
  57872. data.push(0.0);
  57873. }
  57874. }
  57875. // Sprite data
  57876. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57877. -0.5, 0.5, 0, 1,
  57878. -0.5, -0.5, 0, 0,
  57879. 0.5, -0.5, 1, 0]);
  57880. // Buffers
  57881. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57882. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57883. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57884. // Update VAO
  57885. this._updateVAO = [];
  57886. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57887. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57888. // Render VAO
  57889. this._renderVAO = [];
  57890. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57891. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57892. // Links
  57893. this._sourceBuffer = this._buffer0;
  57894. this._targetBuffer = this._buffer1;
  57895. };
  57896. /** @hidden */
  57897. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57898. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57899. if (this._isBillboardBased) {
  57900. defines += "\n#define BILLBOARD";
  57901. }
  57902. if (this._colorGradientsTexture) {
  57903. defines += "\n#define COLORGRADIENTS";
  57904. }
  57905. if (this._sizeGradientsTexture) {
  57906. defines += "\n#define SIZEGRADIENTS";
  57907. }
  57908. if (this._angularSpeedGradientsTexture) {
  57909. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57910. }
  57911. if (this._velocityGradientsTexture) {
  57912. defines += "\n#define VELOCITYGRADIENTS";
  57913. }
  57914. if (this.isAnimationSheetEnabled) {
  57915. defines += "\n#define ANIMATESHEET";
  57916. }
  57917. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57918. return;
  57919. }
  57920. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57921. if (!this._colorGradientsTexture) {
  57922. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57923. }
  57924. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57925. if (!this._isBillboardBased) {
  57926. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57927. }
  57928. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57929. if (this.isAnimationSheetEnabled) {
  57930. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57931. }
  57932. this._updateEffectOptions.defines = defines;
  57933. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57934. };
  57935. /** @hidden */
  57936. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57937. var defines = "";
  57938. if (this._scene.clipPlane) {
  57939. defines = "\n#define CLIPPLANE";
  57940. }
  57941. if (this._isBillboardBased) {
  57942. defines += "\n#define BILLBOARD";
  57943. switch (this.billboardMode) {
  57944. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57945. defines += "\n#define BILLBOARDY";
  57946. break;
  57947. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57948. default:
  57949. break;
  57950. }
  57951. }
  57952. if (this._colorGradientsTexture) {
  57953. defines += "\n#define COLORGRADIENTS";
  57954. }
  57955. if (this.isAnimationSheetEnabled) {
  57956. defines += "\n#define ANIMATESHEET";
  57957. }
  57958. if (this._renderEffect && this._renderEffect.defines === defines) {
  57959. return;
  57960. }
  57961. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57962. };
  57963. /**
  57964. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57965. * @param preWarm defines if we are in the pre-warmimg phase
  57966. */
  57967. GPUParticleSystem.prototype.animate = function (preWarm) {
  57968. if (preWarm === void 0) { preWarm = false; }
  57969. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57970. this._actualFrame += this._timeDelta;
  57971. if (!this._stopped) {
  57972. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57973. this.stop();
  57974. }
  57975. }
  57976. };
  57977. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  57978. var texture = this[textureName];
  57979. if (!factorGradients || !factorGradients.length || texture) {
  57980. return;
  57981. }
  57982. var data = new Float32Array(this._rawTextureWidth);
  57983. for (var x = 0; x < this._rawTextureWidth; x++) {
  57984. var ratio = x / this._rawTextureWidth;
  57985. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  57986. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57987. });
  57988. }
  57989. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57990. };
  57991. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57992. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  57993. };
  57994. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  57995. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  57996. };
  57997. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  57998. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  57999. };
  58000. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  58001. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  58002. return;
  58003. }
  58004. var data = new Uint8Array(this._rawTextureWidth * 4);
  58005. var tmpColor = BABYLON.Tmp.Color4[0];
  58006. for (var x = 0; x < this._rawTextureWidth; x++) {
  58007. var ratio = x / this._rawTextureWidth;
  58008. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  58009. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  58010. data[x * 4] = tmpColor.r * 255;
  58011. data[x * 4 + 1] = tmpColor.g * 255;
  58012. data[x * 4 + 2] = tmpColor.b * 255;
  58013. data[x * 4 + 3] = tmpColor.a * 255;
  58014. });
  58015. }
  58016. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58017. };
  58018. /**
  58019. * Renders the particle system in its current state
  58020. * @param preWarm defines if the system should only update the particles but not render them
  58021. * @returns the current number of particles
  58022. */
  58023. GPUParticleSystem.prototype.render = function (preWarm) {
  58024. if (preWarm === void 0) { preWarm = false; }
  58025. if (!this._started) {
  58026. return 0;
  58027. }
  58028. this._createColorGradientTexture();
  58029. this._createSizeGradientTexture();
  58030. this._createAngularSpeedGradientTexture();
  58031. this._createVelocityGradientTexture();
  58032. this._recreateUpdateEffect();
  58033. this._recreateRenderEffect();
  58034. if (!this.isReady()) {
  58035. return 0;
  58036. }
  58037. if (!preWarm) {
  58038. if (!this._preWarmDone && this.preWarmCycles) {
  58039. for (var index = 0; index < this.preWarmCycles; index++) {
  58040. this.animate(true);
  58041. this.render(true);
  58042. }
  58043. this._preWarmDone = true;
  58044. }
  58045. if (this._currentRenderId === this._scene.getRenderId()) {
  58046. return 0;
  58047. }
  58048. this._currentRenderId = this._scene.getRenderId();
  58049. }
  58050. // Get everything ready to render
  58051. this._initialize();
  58052. this._accumulatedCount += this.emitRate * this._timeDelta;
  58053. if (this._accumulatedCount > 1) {
  58054. var intPart = this._accumulatedCount | 0;
  58055. this._accumulatedCount -= intPart;
  58056. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  58057. }
  58058. if (!this._currentActiveCount) {
  58059. return 0;
  58060. }
  58061. // Enable update effect
  58062. this._engine.enableEffect(this._updateEffect);
  58063. this._engine.setState(false);
  58064. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58065. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58066. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58067. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58068. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  58069. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58070. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58071. if (!this._colorGradientsTexture) {
  58072. this._updateEffect.setDirectColor4("color1", this.color1);
  58073. this._updateEffect.setDirectColor4("color2", this.color2);
  58074. }
  58075. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58076. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  58077. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  58078. this._updateEffect.setVector3("gravity", this.gravity);
  58079. if (this._sizeGradientsTexture) {
  58080. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  58081. }
  58082. if (this._angularSpeedGradientsTexture) {
  58083. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  58084. }
  58085. if (this._velocityGradientsTexture) {
  58086. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  58087. }
  58088. if (this.particleEmitterType) {
  58089. this.particleEmitterType.applyToShader(this._updateEffect);
  58090. }
  58091. if (this._isAnimationSheetEnabled) {
  58092. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  58093. }
  58094. var emitterWM;
  58095. if (this.emitter.position) {
  58096. var emitterMesh = this.emitter;
  58097. emitterWM = emitterMesh.getWorldMatrix();
  58098. }
  58099. else {
  58100. var emitterPosition = this.emitter;
  58101. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58102. }
  58103. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58104. // Bind source VAO
  58105. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58106. // Update
  58107. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58108. this._engine.setRasterizerState(false);
  58109. this._engine.beginTransformFeedback();
  58110. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58111. this._engine.endTransformFeedback();
  58112. this._engine.setRasterizerState(true);
  58113. this._engine.bindTransformFeedbackBuffer(null);
  58114. if (!preWarm) {
  58115. // Enable render effect
  58116. this._engine.enableEffect(this._renderEffect);
  58117. var viewMatrix = this._scene.getViewMatrix();
  58118. this._renderEffect.setMatrix("view", viewMatrix);
  58119. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58120. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58121. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  58122. if (this._colorGradientsTexture) {
  58123. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  58124. }
  58125. else {
  58126. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58127. }
  58128. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58129. var baseSize = this.particleTexture.getBaseSize();
  58130. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58131. }
  58132. if (this._isBillboardBased) {
  58133. var camera = this._scene.activeCamera;
  58134. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  58135. }
  58136. if (this._scene.clipPlane) {
  58137. var clipPlane = this._scene.clipPlane;
  58138. var invView = viewMatrix.clone();
  58139. invView.invert();
  58140. this._renderEffect.setMatrix("invView", invView);
  58141. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58142. }
  58143. // Draw order
  58144. switch (this.blendMode) {
  58145. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  58146. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58147. break;
  58148. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  58149. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58150. break;
  58151. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  58152. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58153. break;
  58154. }
  58155. if (this.forceDepthWrite) {
  58156. this._engine.setDepthWrite(true);
  58157. }
  58158. // Bind source VAO
  58159. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58160. // Render
  58161. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58162. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58163. }
  58164. // Switch VAOs
  58165. this._targetIndex++;
  58166. if (this._targetIndex === 2) {
  58167. this._targetIndex = 0;
  58168. }
  58169. // Switch buffers
  58170. var tmpBuffer = this._sourceBuffer;
  58171. this._sourceBuffer = this._targetBuffer;
  58172. this._targetBuffer = tmpBuffer;
  58173. return this._currentActiveCount;
  58174. };
  58175. /**
  58176. * Rebuilds the particle system
  58177. */
  58178. GPUParticleSystem.prototype.rebuild = function () {
  58179. this._initialize(true);
  58180. };
  58181. GPUParticleSystem.prototype._releaseBuffers = function () {
  58182. if (this._buffer0) {
  58183. this._buffer0.dispose();
  58184. this._buffer0 = null;
  58185. }
  58186. if (this._buffer1) {
  58187. this._buffer1.dispose();
  58188. this._buffer1 = null;
  58189. }
  58190. if (this._spriteBuffer) {
  58191. this._spriteBuffer.dispose();
  58192. this._spriteBuffer = null;
  58193. }
  58194. };
  58195. GPUParticleSystem.prototype._releaseVAOs = function () {
  58196. if (!this._updateVAO) {
  58197. return;
  58198. }
  58199. for (var index = 0; index < this._updateVAO.length; index++) {
  58200. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58201. }
  58202. this._updateVAO = [];
  58203. for (var index = 0; index < this._renderVAO.length; index++) {
  58204. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58205. }
  58206. this._renderVAO = [];
  58207. };
  58208. /**
  58209. * Disposes the particle system and free the associated resources
  58210. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58211. */
  58212. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58213. if (disposeTexture === void 0) { disposeTexture = true; }
  58214. var index = this._scene.particleSystems.indexOf(this);
  58215. if (index > -1) {
  58216. this._scene.particleSystems.splice(index, 1);
  58217. }
  58218. this._releaseBuffers();
  58219. this._releaseVAOs();
  58220. if (this._colorGradientsTexture) {
  58221. this._colorGradientsTexture.dispose();
  58222. this._colorGradientsTexture = null;
  58223. }
  58224. if (this._sizeGradientsTexture) {
  58225. this._sizeGradientsTexture.dispose();
  58226. this._sizeGradientsTexture = null;
  58227. }
  58228. if (this._angularSpeedGradientsTexture) {
  58229. this._angularSpeedGradientsTexture.dispose();
  58230. this._angularSpeedGradientsTexture = null;
  58231. }
  58232. if (this._velocityGradientsTexture) {
  58233. this._velocityGradientsTexture.dispose();
  58234. this._velocityGradientsTexture = null;
  58235. }
  58236. if (this._randomTexture) {
  58237. this._randomTexture.dispose();
  58238. this._randomTexture = null;
  58239. }
  58240. if (this._randomTexture2) {
  58241. this._randomTexture2.dispose();
  58242. this._randomTexture2 = null;
  58243. }
  58244. if (disposeTexture && this.particleTexture) {
  58245. this.particleTexture.dispose();
  58246. this.particleTexture = null;
  58247. }
  58248. // Callback
  58249. this.onDisposeObservable.notifyObservers(this);
  58250. this.onDisposeObservable.clear();
  58251. };
  58252. /**
  58253. * Clones the particle system.
  58254. * @param name The name of the cloned object
  58255. * @param newEmitter The new emitter to use
  58256. * @returns the cloned particle system
  58257. */
  58258. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58259. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58260. BABYLON.Tools.DeepCopy(this, result);
  58261. if (newEmitter === undefined) {
  58262. newEmitter = this.emitter;
  58263. }
  58264. result.emitter = newEmitter;
  58265. if (this.particleTexture) {
  58266. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58267. }
  58268. return result;
  58269. };
  58270. /**
  58271. * Serializes the particle system to a JSON object.
  58272. * @returns the JSON object
  58273. */
  58274. GPUParticleSystem.prototype.serialize = function () {
  58275. var serializationObject = {};
  58276. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  58277. serializationObject.activeParticleCount = this.activeParticleCount;
  58278. return serializationObject;
  58279. };
  58280. /**
  58281. * Parses a JSON object to create a GPU particle system.
  58282. * @param parsedParticleSystem The JSON object to parse
  58283. * @param scene The scene to create the particle system in
  58284. * @param rootUrl The root url to use to load external dependencies like texture
  58285. * @returns the parsed GPU particle system
  58286. */
  58287. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58288. var name = parsedParticleSystem.name;
  58289. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58290. if (parsedParticleSystem.activeParticleCount) {
  58291. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58292. }
  58293. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58294. return particleSystem;
  58295. };
  58296. return GPUParticleSystem;
  58297. }());
  58298. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58299. })(BABYLON || (BABYLON = {}));
  58300. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58301. var BABYLON;
  58302. (function (BABYLON) {
  58303. /**
  58304. * Represents one particle of a solid particle system.
  58305. */
  58306. var SolidParticle = /** @class */ (function () {
  58307. /**
  58308. * Creates a Solid Particle object.
  58309. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58310. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58311. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58312. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58313. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58314. * @param shapeId (integer) is the model shape identifier in the SPS.
  58315. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58316. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58317. */
  58318. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58319. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58320. /**
  58321. * particle global index
  58322. */
  58323. this.idx = 0;
  58324. /**
  58325. * The color of the particle
  58326. */
  58327. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58328. /**
  58329. * The world space position of the particle.
  58330. */
  58331. this.position = BABYLON.Vector3.Zero();
  58332. /**
  58333. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58334. */
  58335. this.rotation = BABYLON.Vector3.Zero();
  58336. /**
  58337. * The scaling of the particle.
  58338. */
  58339. this.scaling = BABYLON.Vector3.One();
  58340. /**
  58341. * The uvs of the particle.
  58342. */
  58343. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58344. /**
  58345. * The current speed of the particle.
  58346. */
  58347. this.velocity = BABYLON.Vector3.Zero();
  58348. /**
  58349. * The pivot point in the particle local space.
  58350. */
  58351. this.pivot = BABYLON.Vector3.Zero();
  58352. /**
  58353. * Must the particle be translated from its pivot point in its local space ?
  58354. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58355. * Default : false
  58356. */
  58357. this.translateFromPivot = false;
  58358. /**
  58359. * Is the particle active or not ?
  58360. */
  58361. this.alive = true;
  58362. /**
  58363. * Is the particle visible or not ?
  58364. */
  58365. this.isVisible = true;
  58366. /**
  58367. * Index of this particle in the global "positions" array (Internal use)
  58368. */
  58369. this._pos = 0;
  58370. /**
  58371. * Index of this particle in the global "indices" array (Internal use)
  58372. */
  58373. this._ind = 0;
  58374. /**
  58375. * ModelShape id of this particle
  58376. */
  58377. this.shapeId = 0;
  58378. /**
  58379. * Index of the particle in its shape id (Internal use)
  58380. */
  58381. this.idxInShape = 0;
  58382. /**
  58383. * Still set as invisible in order to skip useless computations (Internal use)
  58384. */
  58385. this._stillInvisible = false;
  58386. /**
  58387. * Last computed particle rotation matrix
  58388. */
  58389. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58390. /**
  58391. * Parent particle Id, if any.
  58392. * Default null.
  58393. */
  58394. this.parentId = null;
  58395. /**
  58396. * Internal global position in the SPS.
  58397. */
  58398. this._globalPosition = BABYLON.Vector3.Zero();
  58399. this.idx = particleIndex;
  58400. this._pos = positionIndex;
  58401. this._ind = indiceIndex;
  58402. this._model = model;
  58403. this.shapeId = shapeId;
  58404. this.idxInShape = idxInShape;
  58405. this._sps = sps;
  58406. if (modelBoundingInfo) {
  58407. this._modelBoundingInfo = modelBoundingInfo;
  58408. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58409. }
  58410. }
  58411. Object.defineProperty(SolidParticle.prototype, "scale", {
  58412. /**
  58413. * Legacy support, changed scale to scaling
  58414. */
  58415. get: function () {
  58416. return this.scaling;
  58417. },
  58418. /**
  58419. * Legacy support, changed scale to scaling
  58420. */
  58421. set: function (scale) {
  58422. this.scaling = scale;
  58423. },
  58424. enumerable: true,
  58425. configurable: true
  58426. });
  58427. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58428. /**
  58429. * Legacy support, changed quaternion to rotationQuaternion
  58430. */
  58431. get: function () {
  58432. return this.rotationQuaternion;
  58433. },
  58434. /**
  58435. * Legacy support, changed quaternion to rotationQuaternion
  58436. */
  58437. set: function (q) {
  58438. this.rotationQuaternion = q;
  58439. },
  58440. enumerable: true,
  58441. configurable: true
  58442. });
  58443. /**
  58444. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58445. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58446. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58447. * @returns true if it intersects
  58448. */
  58449. SolidParticle.prototype.intersectsMesh = function (target) {
  58450. if (!this._boundingInfo || !target._boundingInfo) {
  58451. return false;
  58452. }
  58453. if (this._sps._bSphereOnly) {
  58454. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58455. }
  58456. return this._boundingInfo.intersects(target._boundingInfo, false);
  58457. };
  58458. return SolidParticle;
  58459. }());
  58460. BABYLON.SolidParticle = SolidParticle;
  58461. /**
  58462. * Represents the shape of the model used by one particle of a solid particle system.
  58463. * SPS internal tool, don't use it manually.
  58464. */
  58465. var ModelShape = /** @class */ (function () {
  58466. /**
  58467. * 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.
  58468. * SPS internal tool, don't use it manually.
  58469. * @hidden
  58470. */
  58471. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58472. /**
  58473. * length of the shape in the model indices array (internal use)
  58474. */
  58475. this._indicesLength = 0;
  58476. this.shapeID = id;
  58477. this._shape = shape;
  58478. this._indicesLength = indicesLength;
  58479. this._shapeUV = shapeUV;
  58480. this._positionFunction = posFunction;
  58481. this._vertexFunction = vtxFunction;
  58482. }
  58483. return ModelShape;
  58484. }());
  58485. BABYLON.ModelShape = ModelShape;
  58486. /**
  58487. * Represents a Depth Sorted Particle in the solid particle system.
  58488. */
  58489. var DepthSortedParticle = /** @class */ (function () {
  58490. function DepthSortedParticle() {
  58491. /**
  58492. * Index of the particle in the "indices" array
  58493. */
  58494. this.ind = 0;
  58495. /**
  58496. * Length of the particle shape in the "indices" array
  58497. */
  58498. this.indicesLength = 0;
  58499. /**
  58500. * Squared distance from the particle to the camera
  58501. */
  58502. this.sqDistance = 0.0;
  58503. }
  58504. return DepthSortedParticle;
  58505. }());
  58506. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58507. })(BABYLON || (BABYLON = {}));
  58508. //# sourceMappingURL=babylon.solidParticle.js.map
  58509. var BABYLON;
  58510. (function (BABYLON) {
  58511. /**
  58512. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58513. *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.
  58514. * The SPS is also a particle system. It provides some methods to manage the particles.
  58515. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58516. *
  58517. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58518. */
  58519. var SolidParticleSystem = /** @class */ (function () {
  58520. /**
  58521. * Creates a SPS (Solid Particle System) object.
  58522. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58523. * @param scene (Scene) is the scene in which the SPS is added.
  58524. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58525. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58526. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58527. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58528. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58529. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58530. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58531. */
  58532. function SolidParticleSystem(name, scene, options) {
  58533. /**
  58534. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58535. * Example : var p = SPS.particles[i];
  58536. */
  58537. this.particles = new Array();
  58538. /**
  58539. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58540. */
  58541. this.nbParticles = 0;
  58542. /**
  58543. * If the particles must ever face the camera (default false). Useful for planar particles.
  58544. */
  58545. this.billboard = false;
  58546. /**
  58547. * Recompute normals when adding a shape
  58548. */
  58549. this.recomputeNormals = true;
  58550. /**
  58551. * This a counter ofr your own usage. It's not set by any SPS functions.
  58552. */
  58553. this.counter = 0;
  58554. /**
  58555. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58556. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58557. */
  58558. this.vars = {};
  58559. /**
  58560. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58561. */
  58562. this._bSphereOnly = false;
  58563. /**
  58564. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58565. */
  58566. this._bSphereRadiusFactor = 1.0;
  58567. this._positions = new Array();
  58568. this._indices = new Array();
  58569. this._normals = new Array();
  58570. this._colors = new Array();
  58571. this._uvs = new Array();
  58572. this._index = 0; // indices index
  58573. this._updatable = true;
  58574. this._pickable = false;
  58575. this._isVisibilityBoxLocked = false;
  58576. this._alwaysVisible = false;
  58577. this._depthSort = false;
  58578. this._shapeCounter = 0;
  58579. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58580. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58581. this._computeParticleColor = true;
  58582. this._computeParticleTexture = true;
  58583. this._computeParticleRotation = true;
  58584. this._computeParticleVertex = false;
  58585. this._computeBoundingBox = false;
  58586. this._depthSortParticles = true;
  58587. this._cam_axisZ = BABYLON.Vector3.Zero();
  58588. this._cam_axisY = BABYLON.Vector3.Zero();
  58589. this._cam_axisX = BABYLON.Vector3.Zero();
  58590. this._axisZ = BABYLON.Axis.Z;
  58591. this._camDir = BABYLON.Vector3.Zero();
  58592. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58593. this._rotMatrix = new BABYLON.Matrix();
  58594. this._invertMatrix = new BABYLON.Matrix();
  58595. this._rotated = BABYLON.Vector3.Zero();
  58596. this._quaternion = new BABYLON.Quaternion();
  58597. this._vertex = BABYLON.Vector3.Zero();
  58598. this._normal = BABYLON.Vector3.Zero();
  58599. this._yaw = 0.0;
  58600. this._pitch = 0.0;
  58601. this._roll = 0.0;
  58602. this._halfroll = 0.0;
  58603. this._halfpitch = 0.0;
  58604. this._halfyaw = 0.0;
  58605. this._sinRoll = 0.0;
  58606. this._cosRoll = 0.0;
  58607. this._sinPitch = 0.0;
  58608. this._cosPitch = 0.0;
  58609. this._sinYaw = 0.0;
  58610. this._cosYaw = 0.0;
  58611. this._mustUnrotateFixedNormals = false;
  58612. this._minimum = BABYLON.Vector3.Zero();
  58613. this._maximum = BABYLON.Vector3.Zero();
  58614. this._minBbox = BABYLON.Vector3.Zero();
  58615. this._maxBbox = BABYLON.Vector3.Zero();
  58616. this._particlesIntersect = false;
  58617. this._depthSortFunction = function (p1, p2) {
  58618. return (p2.sqDistance - p1.sqDistance);
  58619. };
  58620. this._needs32Bits = false;
  58621. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58622. this._scaledPivot = BABYLON.Vector3.Zero();
  58623. this._particleHasParent = false;
  58624. this.name = name;
  58625. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58626. this._camera = scene.activeCamera;
  58627. this._pickable = options ? options.isPickable : false;
  58628. this._depthSort = options ? options.enableDepthSort : false;
  58629. this._particlesIntersect = options ? options.particleIntersection : false;
  58630. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58631. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58632. if (options && options.updatable !== undefined) {
  58633. this._updatable = options.updatable;
  58634. }
  58635. else {
  58636. this._updatable = true;
  58637. }
  58638. if (this._pickable) {
  58639. this.pickedParticles = [];
  58640. }
  58641. if (this._depthSort) {
  58642. this.depthSortedParticles = [];
  58643. }
  58644. }
  58645. /**
  58646. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58647. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58648. * @returns the created mesh
  58649. */
  58650. SolidParticleSystem.prototype.buildMesh = function () {
  58651. if (this.nbParticles === 0) {
  58652. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58653. this.addShape(triangle, 1);
  58654. triangle.dispose();
  58655. }
  58656. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58657. this._positions32 = new Float32Array(this._positions);
  58658. this._uvs32 = new Float32Array(this._uvs);
  58659. this._colors32 = new Float32Array(this._colors);
  58660. if (this.recomputeNormals) {
  58661. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58662. }
  58663. this._normals32 = new Float32Array(this._normals);
  58664. this._fixedNormal32 = new Float32Array(this._normals);
  58665. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58666. this._unrotateFixedNormals();
  58667. }
  58668. var vertexData = new BABYLON.VertexData();
  58669. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58670. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58671. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58672. if (this._uvs32.length > 0) {
  58673. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58674. }
  58675. if (this._colors32.length > 0) {
  58676. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58677. }
  58678. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58679. vertexData.applyToMesh(mesh, this._updatable);
  58680. this.mesh = mesh;
  58681. this.mesh.isPickable = this._pickable;
  58682. // free memory
  58683. if (!this._depthSort) {
  58684. this._indices = null;
  58685. }
  58686. this._positions = null;
  58687. this._normals = null;
  58688. this._uvs = null;
  58689. this._colors = null;
  58690. if (!this._updatable) {
  58691. this.particles.length = 0;
  58692. }
  58693. return mesh;
  58694. };
  58695. /**
  58696. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58697. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58698. * Thus the particles generated from `digest()` have their property `position` set yet.
  58699. * @param mesh ( Mesh ) is the mesh to be digested
  58700. * @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
  58701. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58702. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58703. * @returns the current SPS
  58704. */
  58705. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58706. var size = (options && options.facetNb) || 1;
  58707. var number = (options && options.number) || 0;
  58708. var delta = (options && options.delta) || 0;
  58709. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58710. var meshInd = mesh.getIndices();
  58711. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58712. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58713. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58714. var f = 0; // facet counter
  58715. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58716. // compute size from number
  58717. if (number) {
  58718. number = (number > totalFacets) ? totalFacets : number;
  58719. size = Math.round(totalFacets / number);
  58720. delta = 0;
  58721. }
  58722. else {
  58723. size = (size > totalFacets) ? totalFacets : size;
  58724. }
  58725. var facetPos = []; // submesh positions
  58726. var facetInd = []; // submesh indices
  58727. var facetUV = []; // submesh UV
  58728. var facetCol = []; // submesh colors
  58729. var barycenter = BABYLON.Vector3.Zero();
  58730. var sizeO = size;
  58731. while (f < totalFacets) {
  58732. size = sizeO + Math.floor((1 + delta) * Math.random());
  58733. if (f > totalFacets - size) {
  58734. size = totalFacets - f;
  58735. }
  58736. // reset temp arrays
  58737. facetPos.length = 0;
  58738. facetInd.length = 0;
  58739. facetUV.length = 0;
  58740. facetCol.length = 0;
  58741. // iterate over "size" facets
  58742. var fi = 0;
  58743. for (var j = f * 3; j < (f + size) * 3; j++) {
  58744. facetInd.push(fi);
  58745. var i = meshInd[j];
  58746. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58747. if (meshUV) {
  58748. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58749. }
  58750. if (meshCol) {
  58751. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58752. }
  58753. fi++;
  58754. }
  58755. // create a model shape for each single particle
  58756. var idx = this.nbParticles;
  58757. var shape = this._posToShape(facetPos);
  58758. var shapeUV = this._uvsToShapeUV(facetUV);
  58759. // compute the barycenter of the shape
  58760. var v;
  58761. for (v = 0; v < shape.length; v++) {
  58762. barycenter.addInPlace(shape[v]);
  58763. }
  58764. barycenter.scaleInPlace(1 / shape.length);
  58765. // shift the shape from its barycenter to the origin
  58766. for (v = 0; v < shape.length; v++) {
  58767. shape[v].subtractInPlace(barycenter);
  58768. }
  58769. var bInfo;
  58770. if (this._particlesIntersect) {
  58771. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58772. }
  58773. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58774. // add the particle in the SPS
  58775. var currentPos = this._positions.length;
  58776. var currentInd = this._indices.length;
  58777. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58778. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58779. // initialize the particle position
  58780. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58781. this._index += shape.length;
  58782. idx++;
  58783. this.nbParticles++;
  58784. this._shapeCounter++;
  58785. f += size;
  58786. }
  58787. return this;
  58788. };
  58789. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58790. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58791. var index = 0;
  58792. var idx = 0;
  58793. for (var p = 0; p < this.particles.length; p++) {
  58794. this._particle = this.particles[p];
  58795. this._shape = this._particle._model._shape;
  58796. if (this._particle.rotationQuaternion) {
  58797. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58798. }
  58799. else {
  58800. this._yaw = this._particle.rotation.y;
  58801. this._pitch = this._particle.rotation.x;
  58802. this._roll = this._particle.rotation.z;
  58803. this._quaternionRotationYPR();
  58804. }
  58805. this._quaternionToRotationMatrix();
  58806. this._rotMatrix.invertToRef(this._invertMatrix);
  58807. for (var pt = 0; pt < this._shape.length; pt++) {
  58808. idx = index + pt * 3;
  58809. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58810. this._fixedNormal32[idx] = this._normal.x;
  58811. this._fixedNormal32[idx + 1] = this._normal.y;
  58812. this._fixedNormal32[idx + 2] = this._normal.z;
  58813. }
  58814. index = idx + 3;
  58815. }
  58816. };
  58817. //reset copy
  58818. SolidParticleSystem.prototype._resetCopy = function () {
  58819. this._copy.position.x = 0;
  58820. this._copy.position.y = 0;
  58821. this._copy.position.z = 0;
  58822. this._copy.rotation.x = 0;
  58823. this._copy.rotation.y = 0;
  58824. this._copy.rotation.z = 0;
  58825. this._copy.rotationQuaternion = null;
  58826. this._copy.scaling.x = 1.0;
  58827. this._copy.scaling.y = 1.0;
  58828. this._copy.scaling.z = 1.0;
  58829. this._copy.uvs.x = 0;
  58830. this._copy.uvs.y = 0;
  58831. this._copy.uvs.z = 1.0;
  58832. this._copy.uvs.w = 1.0;
  58833. this._copy.color = null;
  58834. this._copy.translateFromPivot = false;
  58835. };
  58836. // _meshBuilder : inserts the shape model in the global SPS mesh
  58837. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58838. var i;
  58839. var u = 0;
  58840. var c = 0;
  58841. var n = 0;
  58842. this._resetCopy();
  58843. if (options && options.positionFunction) { // call to custom positionFunction
  58844. options.positionFunction(this._copy, idx, idxInShape);
  58845. this._mustUnrotateFixedNormals = true;
  58846. }
  58847. if (this._copy.rotationQuaternion) {
  58848. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58849. }
  58850. else {
  58851. this._yaw = this._copy.rotation.y;
  58852. this._pitch = this._copy.rotation.x;
  58853. this._roll = this._copy.rotation.z;
  58854. this._quaternionRotationYPR();
  58855. }
  58856. this._quaternionToRotationMatrix();
  58857. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58858. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58859. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58860. if (this._copy.translateFromPivot) {
  58861. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58862. }
  58863. else {
  58864. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58865. }
  58866. for (i = 0; i < shape.length; i++) {
  58867. this._vertex.x = shape[i].x;
  58868. this._vertex.y = shape[i].y;
  58869. this._vertex.z = shape[i].z;
  58870. if (options && options.vertexFunction) {
  58871. options.vertexFunction(this._copy, this._vertex, i);
  58872. }
  58873. this._vertex.x *= this._copy.scaling.x;
  58874. this._vertex.y *= this._copy.scaling.y;
  58875. this._vertex.z *= this._copy.scaling.z;
  58876. this._vertex.x -= this._scaledPivot.x;
  58877. this._vertex.y -= this._scaledPivot.y;
  58878. this._vertex.z -= this._scaledPivot.z;
  58879. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58880. this._rotated.addInPlace(this._pivotBackTranslation);
  58881. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58882. if (meshUV) {
  58883. 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);
  58884. u += 2;
  58885. }
  58886. if (this._copy.color) {
  58887. this._color = this._copy.color;
  58888. }
  58889. else if (meshCol && meshCol[c] !== undefined) {
  58890. this._color.r = meshCol[c];
  58891. this._color.g = meshCol[c + 1];
  58892. this._color.b = meshCol[c + 2];
  58893. this._color.a = meshCol[c + 3];
  58894. }
  58895. else {
  58896. this._color.r = 1.0;
  58897. this._color.g = 1.0;
  58898. this._color.b = 1.0;
  58899. this._color.a = 1.0;
  58900. }
  58901. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58902. c += 4;
  58903. if (!this.recomputeNormals && meshNor) {
  58904. this._normal.x = meshNor[n];
  58905. this._normal.y = meshNor[n + 1];
  58906. this._normal.z = meshNor[n + 2];
  58907. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58908. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58909. n += 3;
  58910. }
  58911. }
  58912. for (i = 0; i < meshInd.length; i++) {
  58913. var current_ind = p + meshInd[i];
  58914. indices.push(current_ind);
  58915. if (current_ind > 65535) {
  58916. this._needs32Bits = true;
  58917. }
  58918. }
  58919. if (this._pickable) {
  58920. var nbfaces = meshInd.length / 3;
  58921. for (i = 0; i < nbfaces; i++) {
  58922. this.pickedParticles.push({ idx: idx, faceId: i });
  58923. }
  58924. }
  58925. if (this._depthSort) {
  58926. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58927. }
  58928. return this._copy;
  58929. };
  58930. // returns a shape array from positions array
  58931. SolidParticleSystem.prototype._posToShape = function (positions) {
  58932. var shape = [];
  58933. for (var i = 0; i < positions.length; i += 3) {
  58934. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58935. }
  58936. return shape;
  58937. };
  58938. // returns a shapeUV array from a Vector4 uvs
  58939. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58940. var shapeUV = [];
  58941. if (uvs) {
  58942. for (var i = 0; i < uvs.length; i++)
  58943. shapeUV.push(uvs[i]);
  58944. }
  58945. return shapeUV;
  58946. };
  58947. // adds a new particle object in the particles array
  58948. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58949. if (bInfo === void 0) { bInfo = null; }
  58950. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58951. this.particles.push(sp);
  58952. return sp;
  58953. };
  58954. /**
  58955. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58956. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58957. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58958. * @param nb (positive integer) the number of particles to be created from this model
  58959. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58960. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58961. * @returns the number of shapes in the system
  58962. */
  58963. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58964. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58965. var meshInd = mesh.getIndices();
  58966. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58967. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58968. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58969. var bbInfo;
  58970. if (this._particlesIntersect) {
  58971. bbInfo = mesh.getBoundingInfo();
  58972. }
  58973. var shape = this._posToShape(meshPos);
  58974. var shapeUV = this._uvsToShapeUV(meshUV);
  58975. var posfunc = options ? options.positionFunction : null;
  58976. var vtxfunc = options ? options.vertexFunction : null;
  58977. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58978. // particles
  58979. var sp;
  58980. var currentCopy;
  58981. var idx = this.nbParticles;
  58982. for (var i = 0; i < nb; i++) {
  58983. var currentPos = this._positions.length;
  58984. var currentInd = this._indices.length;
  58985. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58986. if (this._updatable) {
  58987. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58988. sp.position.copyFrom(currentCopy.position);
  58989. sp.rotation.copyFrom(currentCopy.rotation);
  58990. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58991. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58992. }
  58993. if (currentCopy.color && sp.color) {
  58994. sp.color.copyFrom(currentCopy.color);
  58995. }
  58996. sp.scaling.copyFrom(currentCopy.scaling);
  58997. sp.uvs.copyFrom(currentCopy.uvs);
  58998. }
  58999. this._index += shape.length;
  59000. idx++;
  59001. }
  59002. this.nbParticles += nb;
  59003. this._shapeCounter++;
  59004. return this._shapeCounter - 1;
  59005. };
  59006. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59007. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59008. this._resetCopy();
  59009. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59010. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59011. }
  59012. if (this._copy.rotationQuaternion) {
  59013. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59014. }
  59015. else {
  59016. this._yaw = this._copy.rotation.y;
  59017. this._pitch = this._copy.rotation.x;
  59018. this._roll = this._copy.rotation.z;
  59019. this._quaternionRotationYPR();
  59020. }
  59021. this._quaternionToRotationMatrix();
  59022. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59023. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59024. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59025. if (this._copy.translateFromPivot) {
  59026. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59027. }
  59028. else {
  59029. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59030. }
  59031. this._shape = particle._model._shape;
  59032. for (var pt = 0; pt < this._shape.length; pt++) {
  59033. this._vertex.x = this._shape[pt].x;
  59034. this._vertex.y = this._shape[pt].y;
  59035. this._vertex.z = this._shape[pt].z;
  59036. if (particle._model._vertexFunction) {
  59037. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59038. }
  59039. this._vertex.x *= this._copy.scaling.x;
  59040. this._vertex.y *= this._copy.scaling.y;
  59041. this._vertex.z *= this._copy.scaling.z;
  59042. this._vertex.x -= this._scaledPivot.x;
  59043. this._vertex.y -= this._scaledPivot.y;
  59044. this._vertex.z -= this._scaledPivot.z;
  59045. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59046. this._rotated.addInPlace(this._pivotBackTranslation);
  59047. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59048. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59049. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59050. }
  59051. particle.position.x = 0.0;
  59052. particle.position.y = 0.0;
  59053. particle.position.z = 0.0;
  59054. particle.rotation.x = 0.0;
  59055. particle.rotation.y = 0.0;
  59056. particle.rotation.z = 0.0;
  59057. particle.rotationQuaternion = null;
  59058. particle.scaling.x = 1.0;
  59059. particle.scaling.y = 1.0;
  59060. particle.scaling.z = 1.0;
  59061. particle.uvs.x = 0.0;
  59062. particle.uvs.y = 0.0;
  59063. particle.uvs.z = 1.0;
  59064. particle.uvs.w = 1.0;
  59065. particle.pivot.x = 0.0;
  59066. particle.pivot.y = 0.0;
  59067. particle.pivot.z = 0.0;
  59068. particle.translateFromPivot = false;
  59069. particle.parentId = null;
  59070. };
  59071. /**
  59072. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59073. * @returns the SPS.
  59074. */
  59075. SolidParticleSystem.prototype.rebuildMesh = function () {
  59076. for (var p = 0; p < this.particles.length; p++) {
  59077. this._rebuildParticle(this.particles[p]);
  59078. }
  59079. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59080. return this;
  59081. };
  59082. /**
  59083. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59084. * This method calls `updateParticle()` for each particle of the SPS.
  59085. * For an animated SPS, it is usually called within the render loop.
  59086. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59087. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59088. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59089. * @returns the SPS.
  59090. */
  59091. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59092. if (start === void 0) { start = 0; }
  59093. if (end === void 0) { end = this.nbParticles - 1; }
  59094. if (update === void 0) { update = true; }
  59095. if (!this._updatable) {
  59096. return this;
  59097. }
  59098. // custom beforeUpdate
  59099. this.beforeUpdateParticles(start, end, update);
  59100. this._cam_axisX.x = 1.0;
  59101. this._cam_axisX.y = 0.0;
  59102. this._cam_axisX.z = 0.0;
  59103. this._cam_axisY.x = 0.0;
  59104. this._cam_axisY.y = 1.0;
  59105. this._cam_axisY.z = 0.0;
  59106. this._cam_axisZ.x = 0.0;
  59107. this._cam_axisZ.y = 0.0;
  59108. this._cam_axisZ.z = 1.0;
  59109. // cases when the World Matrix is to be computed first
  59110. if (this.billboard || this._depthSort) {
  59111. this.mesh.computeWorldMatrix(true);
  59112. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59113. }
  59114. // if the particles will always face the camera
  59115. if (this.billboard) {
  59116. // compute the camera position and un-rotate it by the current mesh rotation
  59117. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59118. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59119. this._cam_axisZ.normalize();
  59120. // same for camera up vector extracted from the cam view matrix
  59121. var view = this._camera.getViewMatrix(true);
  59122. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59123. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59124. this._cam_axisY.normalize();
  59125. this._cam_axisX.normalize();
  59126. }
  59127. // if depthSort, compute the camera global position in the mesh local system
  59128. if (this._depthSort) {
  59129. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59130. }
  59131. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59132. var idx = 0; // current position index in the global array positions32
  59133. var index = 0; // position start index in the global array positions32 of the current particle
  59134. var colidx = 0; // current color index in the global array colors32
  59135. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59136. var uvidx = 0; // current uv index in the global array uvs32
  59137. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59138. var pt = 0; // current index in the particle model shape
  59139. if (this.mesh.isFacetDataEnabled) {
  59140. this._computeBoundingBox = true;
  59141. }
  59142. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59143. if (this._computeBoundingBox) {
  59144. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59145. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59146. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59147. }
  59148. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59149. if (this.mesh._boundingInfo) {
  59150. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59151. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59152. }
  59153. }
  59154. }
  59155. // particle loop
  59156. index = this.particles[start]._pos;
  59157. var vpos = (index / 3) | 0;
  59158. colorIndex = vpos * 4;
  59159. uvIndex = vpos * 2;
  59160. for (var p = start; p <= end; p++) {
  59161. this._particle = this.particles[p];
  59162. this._shape = this._particle._model._shape;
  59163. this._shapeUV = this._particle._model._shapeUV;
  59164. // call to custom user function to update the particle properties
  59165. this.updateParticle(this._particle);
  59166. // camera-particle distance for depth sorting
  59167. if (this._depthSort && this._depthSortParticles) {
  59168. var dsp = this.depthSortedParticles[p];
  59169. dsp.ind = this._particle._ind;
  59170. dsp.indicesLength = this._particle._model._indicesLength;
  59171. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59172. }
  59173. // skip the computations for inactive or already invisible particles
  59174. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59175. // increment indexes for the next particle
  59176. pt = this._shape.length;
  59177. index += pt * 3;
  59178. colorIndex += pt * 4;
  59179. uvIndex += pt * 2;
  59180. continue;
  59181. }
  59182. if (this._particle.isVisible) {
  59183. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59184. this._particleHasParent = (this._particle.parentId !== null);
  59185. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59186. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59187. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59188. // particle rotation matrix
  59189. if (this.billboard) {
  59190. this._particle.rotation.x = 0.0;
  59191. this._particle.rotation.y = 0.0;
  59192. }
  59193. if (this._computeParticleRotation || this.billboard) {
  59194. if (this._particle.rotationQuaternion) {
  59195. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59196. }
  59197. else {
  59198. this._yaw = this._particle.rotation.y;
  59199. this._pitch = this._particle.rotation.x;
  59200. this._roll = this._particle.rotation.z;
  59201. this._quaternionRotationYPR();
  59202. }
  59203. this._quaternionToRotationMatrix();
  59204. }
  59205. if (this._particleHasParent) {
  59206. this._parent = this.particles[this._particle.parentId];
  59207. 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];
  59208. 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];
  59209. 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];
  59210. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59211. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59212. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59213. if (this._computeParticleRotation || this.billboard) {
  59214. 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];
  59215. 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];
  59216. 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];
  59217. 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];
  59218. 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];
  59219. 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];
  59220. 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];
  59221. 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];
  59222. 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];
  59223. }
  59224. }
  59225. else {
  59226. this._particle._globalPosition.x = this._particle.position.x;
  59227. this._particle._globalPosition.y = this._particle.position.y;
  59228. this._particle._globalPosition.z = this._particle.position.z;
  59229. if (this._computeParticleRotation || this.billboard) {
  59230. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59231. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59232. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59233. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59234. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59235. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59236. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59237. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59238. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59239. }
  59240. }
  59241. if (this._particle.translateFromPivot) {
  59242. this._pivotBackTranslation.x = 0.0;
  59243. this._pivotBackTranslation.y = 0.0;
  59244. this._pivotBackTranslation.z = 0.0;
  59245. }
  59246. else {
  59247. this._pivotBackTranslation.x = this._scaledPivot.x;
  59248. this._pivotBackTranslation.y = this._scaledPivot.y;
  59249. this._pivotBackTranslation.z = this._scaledPivot.z;
  59250. }
  59251. // particle vertex loop
  59252. for (pt = 0; pt < this._shape.length; pt++) {
  59253. idx = index + pt * 3;
  59254. colidx = colorIndex + pt * 4;
  59255. uvidx = uvIndex + pt * 2;
  59256. this._vertex.x = this._shape[pt].x;
  59257. this._vertex.y = this._shape[pt].y;
  59258. this._vertex.z = this._shape[pt].z;
  59259. if (this._computeParticleVertex) {
  59260. this.updateParticleVertex(this._particle, this._vertex, pt);
  59261. }
  59262. // positions
  59263. this._vertex.x *= this._particle.scaling.x;
  59264. this._vertex.y *= this._particle.scaling.y;
  59265. this._vertex.z *= this._particle.scaling.z;
  59266. this._vertex.x -= this._scaledPivot.x;
  59267. this._vertex.y -= this._scaledPivot.y;
  59268. this._vertex.z -= this._scaledPivot.z;
  59269. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59270. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59271. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59272. this._rotated.x += this._pivotBackTranslation.x;
  59273. this._rotated.y += this._pivotBackTranslation.y;
  59274. this._rotated.z += this._pivotBackTranslation.z;
  59275. 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;
  59276. 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;
  59277. 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;
  59278. if (this._computeBoundingBox) {
  59279. if (this._positions32[idx] < this._minimum.x) {
  59280. this._minimum.x = this._positions32[idx];
  59281. }
  59282. if (this._positions32[idx] > this._maximum.x) {
  59283. this._maximum.x = this._positions32[idx];
  59284. }
  59285. if (this._positions32[idx + 1] < this._minimum.y) {
  59286. this._minimum.y = this._positions32[idx + 1];
  59287. }
  59288. if (this._positions32[idx + 1] > this._maximum.y) {
  59289. this._maximum.y = this._positions32[idx + 1];
  59290. }
  59291. if (this._positions32[idx + 2] < this._minimum.z) {
  59292. this._minimum.z = this._positions32[idx + 2];
  59293. }
  59294. if (this._positions32[idx + 2] > this._maximum.z) {
  59295. this._maximum.z = this._positions32[idx + 2];
  59296. }
  59297. }
  59298. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59299. if (!this._computeParticleVertex) {
  59300. this._normal.x = this._fixedNormal32[idx];
  59301. this._normal.y = this._fixedNormal32[idx + 1];
  59302. this._normal.z = this._fixedNormal32[idx + 2];
  59303. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59304. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59305. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59306. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59307. 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;
  59308. 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;
  59309. }
  59310. if (this._computeParticleColor && this._particle.color) {
  59311. this._colors32[colidx] = this._particle.color.r;
  59312. this._colors32[colidx + 1] = this._particle.color.g;
  59313. this._colors32[colidx + 2] = this._particle.color.b;
  59314. this._colors32[colidx + 3] = this._particle.color.a;
  59315. }
  59316. if (this._computeParticleTexture) {
  59317. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59318. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59319. }
  59320. }
  59321. }
  59322. // particle just set invisible : scaled to zero and positioned at the origin
  59323. else {
  59324. this._particle._stillInvisible = true; // mark the particle as invisible
  59325. for (pt = 0; pt < this._shape.length; pt++) {
  59326. idx = index + pt * 3;
  59327. colidx = colorIndex + pt * 4;
  59328. uvidx = uvIndex + pt * 2;
  59329. this._positions32[idx] = 0.0;
  59330. this._positions32[idx + 1] = 0.0;
  59331. this._positions32[idx + 2] = 0.0;
  59332. this._normals32[idx] = 0.0;
  59333. this._normals32[idx + 1] = 0.0;
  59334. this._normals32[idx + 2] = 0.0;
  59335. if (this._computeParticleColor && this._particle.color) {
  59336. this._colors32[colidx] = this._particle.color.r;
  59337. this._colors32[colidx + 1] = this._particle.color.g;
  59338. this._colors32[colidx + 2] = this._particle.color.b;
  59339. this._colors32[colidx + 3] = this._particle.color.a;
  59340. }
  59341. if (this._computeParticleTexture) {
  59342. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59343. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59344. }
  59345. }
  59346. }
  59347. // if the particle intersections must be computed : update the bbInfo
  59348. if (this._particlesIntersect) {
  59349. var bInfo = this._particle._boundingInfo;
  59350. var bBox = bInfo.boundingBox;
  59351. var bSphere = bInfo.boundingSphere;
  59352. if (!this._bSphereOnly) {
  59353. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59354. for (var b = 0; b < bBox.vectors.length; b++) {
  59355. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59356. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59357. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59358. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59359. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59360. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59361. 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;
  59362. 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;
  59363. 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;
  59364. }
  59365. bBox._update(this.mesh._worldMatrix);
  59366. }
  59367. // place and scale the particle bouding sphere in the SPS local system, then update it
  59368. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59369. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59370. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59371. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59372. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59373. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59374. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59375. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59376. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59377. 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));
  59378. bSphere._update(this.mesh._worldMatrix);
  59379. }
  59380. // increment indexes for the next particle
  59381. index = idx + 3;
  59382. colorIndex = colidx + 4;
  59383. uvIndex = uvidx + 2;
  59384. }
  59385. // if the VBO must be updated
  59386. if (update) {
  59387. if (this._computeParticleColor) {
  59388. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59389. }
  59390. if (this._computeParticleTexture) {
  59391. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59392. }
  59393. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59394. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59395. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59396. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59397. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59398. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59399. for (var i = 0; i < this._normals32.length; i++) {
  59400. this._fixedNormal32[i] = this._normals32[i];
  59401. }
  59402. }
  59403. if (!this.mesh.areNormalsFrozen) {
  59404. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59405. }
  59406. }
  59407. if (this._depthSort && this._depthSortParticles) {
  59408. this.depthSortedParticles.sort(this._depthSortFunction);
  59409. var dspl = this.depthSortedParticles.length;
  59410. var sorted = 0;
  59411. var lind = 0;
  59412. var sind = 0;
  59413. var sid = 0;
  59414. for (sorted = 0; sorted < dspl; sorted++) {
  59415. lind = this.depthSortedParticles[sorted].indicesLength;
  59416. sind = this.depthSortedParticles[sorted].ind;
  59417. for (var i = 0; i < lind; i++) {
  59418. this._indices32[sid] = this._indices[sind + i];
  59419. sid++;
  59420. }
  59421. }
  59422. this.mesh.updateIndices(this._indices32);
  59423. }
  59424. }
  59425. if (this._computeBoundingBox) {
  59426. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59427. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59428. }
  59429. this.afterUpdateParticles(start, end, update);
  59430. return this;
  59431. };
  59432. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59433. this._halfroll = this._roll * 0.5;
  59434. this._halfpitch = this._pitch * 0.5;
  59435. this._halfyaw = this._yaw * 0.5;
  59436. this._sinRoll = Math.sin(this._halfroll);
  59437. this._cosRoll = Math.cos(this._halfroll);
  59438. this._sinPitch = Math.sin(this._halfpitch);
  59439. this._cosPitch = Math.cos(this._halfpitch);
  59440. this._sinYaw = Math.sin(this._halfyaw);
  59441. this._cosYaw = Math.cos(this._halfyaw);
  59442. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59443. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59444. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59445. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59446. };
  59447. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59448. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59449. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59450. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59451. this._rotMatrix.m[3] = 0;
  59452. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59453. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59454. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59455. this._rotMatrix.m[7] = 0;
  59456. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59457. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59458. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59459. this._rotMatrix.m[11] = 0;
  59460. this._rotMatrix.m[12] = 0;
  59461. this._rotMatrix.m[13] = 0;
  59462. this._rotMatrix.m[14] = 0;
  59463. this._rotMatrix.m[15] = 1.0;
  59464. };
  59465. /**
  59466. * Disposes the SPS.
  59467. */
  59468. SolidParticleSystem.prototype.dispose = function () {
  59469. this.mesh.dispose();
  59470. this.vars = null;
  59471. // drop references to internal big arrays for the GC
  59472. this._positions = null;
  59473. this._indices = null;
  59474. this._normals = null;
  59475. this._uvs = null;
  59476. this._colors = null;
  59477. this._indices32 = null;
  59478. this._positions32 = null;
  59479. this._normals32 = null;
  59480. this._fixedNormal32 = null;
  59481. this._uvs32 = null;
  59482. this._colors32 = null;
  59483. this.pickedParticles = null;
  59484. };
  59485. /**
  59486. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59487. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59488. * @returns the SPS.
  59489. */
  59490. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59491. if (!this._isVisibilityBoxLocked) {
  59492. this.mesh.refreshBoundingInfo();
  59493. }
  59494. return this;
  59495. };
  59496. /**
  59497. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59498. * @param size the size (float) of the visibility box
  59499. * note : this doesn't lock the SPS mesh bounding box.
  59500. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59501. */
  59502. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59503. var vis = size / 2;
  59504. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59505. };
  59506. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59507. /**
  59508. * Gets whether the SPS as always visible or not
  59509. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59510. */
  59511. get: function () {
  59512. return this._alwaysVisible;
  59513. },
  59514. /**
  59515. * Sets the SPS as always visible or not
  59516. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59517. */
  59518. set: function (val) {
  59519. this._alwaysVisible = val;
  59520. this.mesh.alwaysSelectAsActiveMesh = val;
  59521. },
  59522. enumerable: true,
  59523. configurable: true
  59524. });
  59525. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59526. /**
  59527. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59528. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59529. */
  59530. get: function () {
  59531. return this._isVisibilityBoxLocked;
  59532. },
  59533. /**
  59534. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59535. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59536. */
  59537. set: function (val) {
  59538. this._isVisibilityBoxLocked = val;
  59539. var boundingInfo = this.mesh.getBoundingInfo();
  59540. boundingInfo.isLocked = val;
  59541. },
  59542. enumerable: true,
  59543. configurable: true
  59544. });
  59545. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59546. /**
  59547. * Gets if `setParticles()` computes the particle rotations or not.
  59548. * Default value : true. The SPS is faster when it's set to false.
  59549. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59550. */
  59551. get: function () {
  59552. return this._computeParticleRotation;
  59553. },
  59554. /**
  59555. * Tells to `setParticles()` to compute the particle rotations or not.
  59556. * Default value : true. The SPS is faster when it's set to false.
  59557. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59558. */
  59559. set: function (val) {
  59560. this._computeParticleRotation = val;
  59561. },
  59562. enumerable: true,
  59563. configurable: true
  59564. });
  59565. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59566. /**
  59567. * Gets if `setParticles()` computes the particle colors or not.
  59568. * Default value : true. The SPS is faster when it's set to false.
  59569. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59570. */
  59571. get: function () {
  59572. return this._computeParticleColor;
  59573. },
  59574. /**
  59575. * Tells to `setParticles()` to compute the particle colors or not.
  59576. * Default value : true. The SPS is faster when it's set to false.
  59577. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59578. */
  59579. set: function (val) {
  59580. this._computeParticleColor = val;
  59581. },
  59582. enumerable: true,
  59583. configurable: true
  59584. });
  59585. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59586. /**
  59587. * Gets if `setParticles()` computes the particle textures or not.
  59588. * Default value : true. The SPS is faster when it's set to false.
  59589. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59590. */
  59591. get: function () {
  59592. return this._computeParticleTexture;
  59593. },
  59594. set: function (val) {
  59595. this._computeParticleTexture = val;
  59596. },
  59597. enumerable: true,
  59598. configurable: true
  59599. });
  59600. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59601. /**
  59602. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59603. * Default value : false. The SPS is faster when it's set to false.
  59604. * Note : the particle custom vertex positions aren't stored values.
  59605. */
  59606. get: function () {
  59607. return this._computeParticleVertex;
  59608. },
  59609. /**
  59610. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59611. * Default value : false. The SPS is faster when it's set to false.
  59612. * Note : the particle custom vertex positions aren't stored values.
  59613. */
  59614. set: function (val) {
  59615. this._computeParticleVertex = val;
  59616. },
  59617. enumerable: true,
  59618. configurable: true
  59619. });
  59620. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59621. /**
  59622. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59623. */
  59624. get: function () {
  59625. return this._computeBoundingBox;
  59626. },
  59627. /**
  59628. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59629. */
  59630. set: function (val) {
  59631. this._computeBoundingBox = val;
  59632. },
  59633. enumerable: true,
  59634. configurable: true
  59635. });
  59636. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59637. /**
  59638. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59639. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59640. * Default : `true`
  59641. */
  59642. get: function () {
  59643. return this._depthSortParticles;
  59644. },
  59645. /**
  59646. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59647. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59648. * Default : `true`
  59649. */
  59650. set: function (val) {
  59651. this._depthSortParticles = val;
  59652. },
  59653. enumerable: true,
  59654. configurable: true
  59655. });
  59656. // =======================================================================
  59657. // Particle behavior logic
  59658. // these following methods may be overwritten by the user to fit his needs
  59659. /**
  59660. * This function does nothing. It may be overwritten to set all the particle first values.
  59661. * The SPS doesn't call this function, you may have to call it by your own.
  59662. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59663. */
  59664. SolidParticleSystem.prototype.initParticles = function () {
  59665. };
  59666. /**
  59667. * This function does nothing. It may be overwritten to recycle a particle.
  59668. * The SPS doesn't call this function, you may have to call it by your own.
  59669. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59670. * @param particle The particle to recycle
  59671. * @returns the recycled particle
  59672. */
  59673. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59674. return particle;
  59675. };
  59676. /**
  59677. * Updates a particle : this function should be overwritten by the user.
  59678. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59679. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59680. * @example : just set a particle position or velocity and recycle conditions
  59681. * @param particle The particle to update
  59682. * @returns the updated particle
  59683. */
  59684. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59685. return particle;
  59686. };
  59687. /**
  59688. * Updates a vertex of a particle : it can be overwritten by the user.
  59689. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59690. * @param particle the current particle
  59691. * @param vertex the current index of the current particle
  59692. * @param pt the index of the current vertex in the particle shape
  59693. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59694. * @example : just set a vertex particle position
  59695. * @returns the updated vertex
  59696. */
  59697. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59698. return vertex;
  59699. };
  59700. /**
  59701. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59702. * This does nothing and may be overwritten by the user.
  59703. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59704. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59705. * @param update the boolean update value actually passed to setParticles()
  59706. */
  59707. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59708. };
  59709. /**
  59710. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59711. * This will be passed three parameters.
  59712. * This does nothing and may be overwritten by the user.
  59713. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59714. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59715. * @param update the boolean update value actually passed to setParticles()
  59716. */
  59717. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59718. };
  59719. return SolidParticleSystem;
  59720. }());
  59721. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59722. })(BABYLON || (BABYLON = {}));
  59723. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59724. var BABYLON;
  59725. (function (BABYLON) {
  59726. var ShaderMaterial = /** @class */ (function (_super) {
  59727. __extends(ShaderMaterial, _super);
  59728. function ShaderMaterial(name, scene, shaderPath, options) {
  59729. var _this = _super.call(this, name, scene) || this;
  59730. _this._textures = {};
  59731. _this._textureArrays = {};
  59732. _this._floats = {};
  59733. _this._ints = {};
  59734. _this._floatsArrays = {};
  59735. _this._colors3 = {};
  59736. _this._colors3Arrays = {};
  59737. _this._colors4 = {};
  59738. _this._vectors2 = {};
  59739. _this._vectors3 = {};
  59740. _this._vectors4 = {};
  59741. _this._matrices = {};
  59742. _this._matrices3x3 = {};
  59743. _this._matrices2x2 = {};
  59744. _this._vectors2Arrays = {};
  59745. _this._vectors3Arrays = {};
  59746. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59747. _this._shaderPath = shaderPath;
  59748. options.needAlphaBlending = options.needAlphaBlending || false;
  59749. options.needAlphaTesting = options.needAlphaTesting || false;
  59750. options.attributes = options.attributes || ["position", "normal", "uv"];
  59751. options.uniforms = options.uniforms || ["worldViewProjection"];
  59752. options.uniformBuffers = options.uniformBuffers || [];
  59753. options.samplers = options.samplers || [];
  59754. options.defines = options.defines || [];
  59755. _this._options = options;
  59756. return _this;
  59757. }
  59758. ShaderMaterial.prototype.getClassName = function () {
  59759. return "ShaderMaterial";
  59760. };
  59761. ShaderMaterial.prototype.needAlphaBlending = function () {
  59762. return this._options.needAlphaBlending;
  59763. };
  59764. ShaderMaterial.prototype.needAlphaTesting = function () {
  59765. return this._options.needAlphaTesting;
  59766. };
  59767. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59768. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59769. this._options.uniforms.push(uniformName);
  59770. }
  59771. };
  59772. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59773. if (this._options.samplers.indexOf(name) === -1) {
  59774. this._options.samplers.push(name);
  59775. }
  59776. this._textures[name] = texture;
  59777. return this;
  59778. };
  59779. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59780. if (this._options.samplers.indexOf(name) === -1) {
  59781. this._options.samplers.push(name);
  59782. }
  59783. this._checkUniform(name);
  59784. this._textureArrays[name] = textures;
  59785. return this;
  59786. };
  59787. ShaderMaterial.prototype.setFloat = function (name, value) {
  59788. this._checkUniform(name);
  59789. this._floats[name] = value;
  59790. return this;
  59791. };
  59792. ShaderMaterial.prototype.setInt = function (name, value) {
  59793. this._checkUniform(name);
  59794. this._ints[name] = value;
  59795. return this;
  59796. };
  59797. ShaderMaterial.prototype.setFloats = function (name, value) {
  59798. this._checkUniform(name);
  59799. this._floatsArrays[name] = value;
  59800. return this;
  59801. };
  59802. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59803. this._checkUniform(name);
  59804. this._colors3[name] = value;
  59805. return this;
  59806. };
  59807. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59808. this._checkUniform(name);
  59809. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59810. color.toArray(arr, arr.length);
  59811. return arr;
  59812. }, []);
  59813. return this;
  59814. };
  59815. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59816. this._checkUniform(name);
  59817. this._colors4[name] = value;
  59818. return this;
  59819. };
  59820. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59821. this._checkUniform(name);
  59822. this._vectors2[name] = value;
  59823. return this;
  59824. };
  59825. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59826. this._checkUniform(name);
  59827. this._vectors3[name] = value;
  59828. return this;
  59829. };
  59830. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59831. this._checkUniform(name);
  59832. this._vectors4[name] = value;
  59833. return this;
  59834. };
  59835. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59836. this._checkUniform(name);
  59837. this._matrices[name] = value;
  59838. return this;
  59839. };
  59840. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59841. this._checkUniform(name);
  59842. this._matrices3x3[name] = value;
  59843. return this;
  59844. };
  59845. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59846. this._checkUniform(name);
  59847. this._matrices2x2[name] = value;
  59848. return this;
  59849. };
  59850. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59851. this._checkUniform(name);
  59852. this._vectors2Arrays[name] = value;
  59853. return this;
  59854. };
  59855. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59856. this._checkUniform(name);
  59857. this._vectors3Arrays[name] = value;
  59858. return this;
  59859. };
  59860. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59861. if (!mesh) {
  59862. return true;
  59863. }
  59864. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59865. return false;
  59866. }
  59867. return false;
  59868. };
  59869. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59870. var scene = this.getScene();
  59871. var engine = scene.getEngine();
  59872. if (!this.checkReadyOnEveryCall) {
  59873. if (this._renderId === scene.getRenderId()) {
  59874. if (this._checkCache(scene, mesh, useInstances)) {
  59875. return true;
  59876. }
  59877. }
  59878. }
  59879. // Instances
  59880. var defines = [];
  59881. var attribs = [];
  59882. var fallbacks = new BABYLON.EffectFallbacks();
  59883. if (useInstances) {
  59884. defines.push("#define INSTANCES");
  59885. }
  59886. for (var index = 0; index < this._options.defines.length; index++) {
  59887. defines.push(this._options.defines[index]);
  59888. }
  59889. for (var index = 0; index < this._options.attributes.length; index++) {
  59890. attribs.push(this._options.attributes[index]);
  59891. }
  59892. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59893. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59894. defines.push("#define VERTEXCOLOR");
  59895. }
  59896. // Bones
  59897. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59898. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59899. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59900. if (mesh.numBoneInfluencers > 4) {
  59901. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59902. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59903. }
  59904. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59905. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59906. fallbacks.addCPUSkinningFallback(0, mesh);
  59907. if (this._options.uniforms.indexOf("mBones") === -1) {
  59908. this._options.uniforms.push("mBones");
  59909. }
  59910. }
  59911. else {
  59912. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59913. }
  59914. // Textures
  59915. for (var name in this._textures) {
  59916. if (!this._textures[name].isReady()) {
  59917. return false;
  59918. }
  59919. }
  59920. // Alpha test
  59921. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59922. defines.push("#define ALPHATEST");
  59923. }
  59924. var previousEffect = this._effect;
  59925. var join = defines.join("\n");
  59926. this._effect = engine.createEffect(this._shaderPath, {
  59927. attributes: attribs,
  59928. uniformsNames: this._options.uniforms,
  59929. uniformBuffersNames: this._options.uniformBuffers,
  59930. samplers: this._options.samplers,
  59931. defines: join,
  59932. fallbacks: fallbacks,
  59933. onCompiled: this.onCompiled,
  59934. onError: this.onError
  59935. }, engine);
  59936. if (!this._effect.isReady()) {
  59937. return false;
  59938. }
  59939. if (previousEffect !== this._effect) {
  59940. scene.resetCachedMaterial();
  59941. }
  59942. this._renderId = scene.getRenderId();
  59943. return true;
  59944. };
  59945. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59946. var scene = this.getScene();
  59947. if (!this._effect) {
  59948. return;
  59949. }
  59950. if (this._options.uniforms.indexOf("world") !== -1) {
  59951. this._effect.setMatrix("world", world);
  59952. }
  59953. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59954. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59955. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59956. }
  59957. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59958. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59959. }
  59960. };
  59961. ShaderMaterial.prototype.bind = function (world, mesh) {
  59962. // Std values
  59963. this.bindOnlyWorldMatrix(world);
  59964. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59965. if (this._options.uniforms.indexOf("view") !== -1) {
  59966. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59967. }
  59968. if (this._options.uniforms.indexOf("projection") !== -1) {
  59969. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59970. }
  59971. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59972. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59973. }
  59974. // Bones
  59975. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59976. var name;
  59977. // Texture
  59978. for (name in this._textures) {
  59979. this._effect.setTexture(name, this._textures[name]);
  59980. }
  59981. // Texture arrays
  59982. for (name in this._textureArrays) {
  59983. this._effect.setTextureArray(name, this._textureArrays[name]);
  59984. }
  59985. // Int
  59986. for (name in this._ints) {
  59987. this._effect.setInt(name, this._ints[name]);
  59988. }
  59989. // Float
  59990. for (name in this._floats) {
  59991. this._effect.setFloat(name, this._floats[name]);
  59992. }
  59993. // Floats
  59994. for (name in this._floatsArrays) {
  59995. this._effect.setArray(name, this._floatsArrays[name]);
  59996. }
  59997. // Color3
  59998. for (name in this._colors3) {
  59999. this._effect.setColor3(name, this._colors3[name]);
  60000. }
  60001. for (name in this._colors3Arrays) {
  60002. this._effect.setArray3(name, this._colors3Arrays[name]);
  60003. }
  60004. // Color4
  60005. for (name in this._colors4) {
  60006. var color = this._colors4[name];
  60007. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60008. }
  60009. // Vector2
  60010. for (name in this._vectors2) {
  60011. this._effect.setVector2(name, this._vectors2[name]);
  60012. }
  60013. // Vector3
  60014. for (name in this._vectors3) {
  60015. this._effect.setVector3(name, this._vectors3[name]);
  60016. }
  60017. // Vector4
  60018. for (name in this._vectors4) {
  60019. this._effect.setVector4(name, this._vectors4[name]);
  60020. }
  60021. // Matrix
  60022. for (name in this._matrices) {
  60023. this._effect.setMatrix(name, this._matrices[name]);
  60024. }
  60025. // Matrix 3x3
  60026. for (name in this._matrices3x3) {
  60027. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60028. }
  60029. // Matrix 2x2
  60030. for (name in this._matrices2x2) {
  60031. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60032. }
  60033. // Vector2Array
  60034. for (name in this._vectors2Arrays) {
  60035. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60036. }
  60037. // Vector3Array
  60038. for (name in this._vectors3Arrays) {
  60039. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60040. }
  60041. }
  60042. this._afterBind(mesh);
  60043. };
  60044. ShaderMaterial.prototype.getActiveTextures = function () {
  60045. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60046. for (var name in this._textures) {
  60047. activeTextures.push(this._textures[name]);
  60048. }
  60049. for (var name in this._textureArrays) {
  60050. var array = this._textureArrays[name];
  60051. for (var index = 0; index < array.length; index++) {
  60052. activeTextures.push(array[index]);
  60053. }
  60054. }
  60055. return activeTextures;
  60056. };
  60057. ShaderMaterial.prototype.hasTexture = function (texture) {
  60058. if (_super.prototype.hasTexture.call(this, texture)) {
  60059. return true;
  60060. }
  60061. for (var name in this._textures) {
  60062. if (this._textures[name] === texture) {
  60063. return true;
  60064. }
  60065. }
  60066. for (var name in this._textureArrays) {
  60067. var array = this._textureArrays[name];
  60068. for (var index = 0; index < array.length; index++) {
  60069. if (array[index] === texture) {
  60070. return true;
  60071. }
  60072. }
  60073. }
  60074. return false;
  60075. };
  60076. ShaderMaterial.prototype.clone = function (name) {
  60077. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60078. return newShaderMaterial;
  60079. };
  60080. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60081. if (forceDisposeTextures) {
  60082. var name;
  60083. for (name in this._textures) {
  60084. this._textures[name].dispose();
  60085. }
  60086. for (name in this._textureArrays) {
  60087. var array = this._textureArrays[name];
  60088. for (var index = 0; index < array.length; index++) {
  60089. array[index].dispose();
  60090. }
  60091. }
  60092. }
  60093. this._textures = {};
  60094. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60095. };
  60096. ShaderMaterial.prototype.serialize = function () {
  60097. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60098. serializationObject.customType = "BABYLON.ShaderMaterial";
  60099. serializationObject.options = this._options;
  60100. serializationObject.shaderPath = this._shaderPath;
  60101. var name;
  60102. // Texture
  60103. serializationObject.textures = {};
  60104. for (name in this._textures) {
  60105. serializationObject.textures[name] = this._textures[name].serialize();
  60106. }
  60107. // Texture arrays
  60108. serializationObject.textureArrays = {};
  60109. for (name in this._textureArrays) {
  60110. serializationObject.textureArrays[name] = [];
  60111. var array = this._textureArrays[name];
  60112. for (var index = 0; index < array.length; index++) {
  60113. serializationObject.textureArrays[name].push(array[index].serialize());
  60114. }
  60115. }
  60116. // Float
  60117. serializationObject.floats = {};
  60118. for (name in this._floats) {
  60119. serializationObject.floats[name] = this._floats[name];
  60120. }
  60121. // Float s
  60122. serializationObject.FloatArrays = {};
  60123. for (name in this._floatsArrays) {
  60124. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60125. }
  60126. // Color3
  60127. serializationObject.colors3 = {};
  60128. for (name in this._colors3) {
  60129. serializationObject.colors3[name] = this._colors3[name].asArray();
  60130. }
  60131. // Color3 array
  60132. serializationObject.colors3Arrays = {};
  60133. for (name in this._colors3Arrays) {
  60134. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60135. }
  60136. // Color4
  60137. serializationObject.colors4 = {};
  60138. for (name in this._colors4) {
  60139. serializationObject.colors4[name] = this._colors4[name].asArray();
  60140. }
  60141. // Vector2
  60142. serializationObject.vectors2 = {};
  60143. for (name in this._vectors2) {
  60144. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60145. }
  60146. // Vector3
  60147. serializationObject.vectors3 = {};
  60148. for (name in this._vectors3) {
  60149. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60150. }
  60151. // Vector4
  60152. serializationObject.vectors4 = {};
  60153. for (name in this._vectors4) {
  60154. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60155. }
  60156. // Matrix
  60157. serializationObject.matrices = {};
  60158. for (name in this._matrices) {
  60159. serializationObject.matrices[name] = this._matrices[name].asArray();
  60160. }
  60161. // Matrix 3x3
  60162. serializationObject.matrices3x3 = {};
  60163. for (name in this._matrices3x3) {
  60164. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60165. }
  60166. // Matrix 2x2
  60167. serializationObject.matrices2x2 = {};
  60168. for (name in this._matrices2x2) {
  60169. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60170. }
  60171. // Vector2Array
  60172. serializationObject.vectors2Arrays = {};
  60173. for (name in this._vectors2Arrays) {
  60174. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60175. }
  60176. // Vector3Array
  60177. serializationObject.vectors3Arrays = {};
  60178. for (name in this._vectors3Arrays) {
  60179. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60180. }
  60181. return serializationObject;
  60182. };
  60183. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60184. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60185. var name;
  60186. // Texture
  60187. for (name in source.textures) {
  60188. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60189. }
  60190. // Texture arrays
  60191. for (name in source.textureArrays) {
  60192. var array = source.textureArrays[name];
  60193. var textureArray = new Array();
  60194. for (var index = 0; index < array.length; index++) {
  60195. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60196. }
  60197. material.setTextureArray(name, textureArray);
  60198. }
  60199. // Float
  60200. for (name in source.floats) {
  60201. material.setFloat(name, source.floats[name]);
  60202. }
  60203. // Float s
  60204. for (name in source.floatsArrays) {
  60205. material.setFloats(name, source.floatsArrays[name]);
  60206. }
  60207. // Color3
  60208. for (name in source.colors3) {
  60209. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60210. }
  60211. // Color3 arrays
  60212. for (name in source.colors3Arrays) {
  60213. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60214. if (i % 3 === 0) {
  60215. arr.push([num]);
  60216. }
  60217. else {
  60218. arr[arr.length - 1].push(num);
  60219. }
  60220. return arr;
  60221. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60222. material.setColor3Array(name, colors);
  60223. }
  60224. // Color4
  60225. for (name in source.colors4) {
  60226. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60227. }
  60228. // Vector2
  60229. for (name in source.vectors2) {
  60230. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60231. }
  60232. // Vector3
  60233. for (name in source.vectors3) {
  60234. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60235. }
  60236. // Vector4
  60237. for (name in source.vectors4) {
  60238. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60239. }
  60240. // Matrix
  60241. for (name in source.matrices) {
  60242. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60243. }
  60244. // Matrix 3x3
  60245. for (name in source.matrices3x3) {
  60246. material.setMatrix3x3(name, source.matrices3x3[name]);
  60247. }
  60248. // Matrix 2x2
  60249. for (name in source.matrices2x2) {
  60250. material.setMatrix2x2(name, source.matrices2x2[name]);
  60251. }
  60252. // Vector2Array
  60253. for (name in source.vectors2Arrays) {
  60254. material.setArray2(name, source.vectors2Arrays[name]);
  60255. }
  60256. // Vector3Array
  60257. for (name in source.vectors3Arrays) {
  60258. material.setArray3(name, source.vectors3Arrays[name]);
  60259. }
  60260. return material;
  60261. };
  60262. return ShaderMaterial;
  60263. }(BABYLON.Material));
  60264. BABYLON.ShaderMaterial = ShaderMaterial;
  60265. })(BABYLON || (BABYLON = {}));
  60266. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60267. var BABYLON;
  60268. (function (BABYLON) {
  60269. var GroundMesh = /** @class */ (function (_super) {
  60270. __extends(GroundMesh, _super);
  60271. function GroundMesh(name, scene) {
  60272. var _this = _super.call(this, name, scene) || this;
  60273. _this.generateOctree = false;
  60274. return _this;
  60275. }
  60276. GroundMesh.prototype.getClassName = function () {
  60277. return "GroundMesh";
  60278. };
  60279. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60280. get: function () {
  60281. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60282. },
  60283. enumerable: true,
  60284. configurable: true
  60285. });
  60286. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60287. get: function () {
  60288. return this._subdivisionsX;
  60289. },
  60290. enumerable: true,
  60291. configurable: true
  60292. });
  60293. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60294. get: function () {
  60295. return this._subdivisionsY;
  60296. },
  60297. enumerable: true,
  60298. configurable: true
  60299. });
  60300. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60301. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60302. this._subdivisionsX = chunksCount;
  60303. this._subdivisionsY = chunksCount;
  60304. this.subdivide(chunksCount);
  60305. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60306. };
  60307. /**
  60308. * Returns a height (y) value in the Worl system :
  60309. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60310. * Returns the ground y position if (x, z) are outside the ground surface.
  60311. */
  60312. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60313. var world = this.getWorldMatrix();
  60314. var invMat = BABYLON.Tmp.Matrix[5];
  60315. world.invertToRef(invMat);
  60316. var tmpVect = BABYLON.Tmp.Vector3[8];
  60317. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60318. x = tmpVect.x;
  60319. z = tmpVect.z;
  60320. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60321. return this.position.y;
  60322. }
  60323. if (!this._heightQuads || this._heightQuads.length == 0) {
  60324. this._initHeightQuads();
  60325. this._computeHeightQuads();
  60326. }
  60327. var facet = this._getFacetAt(x, z);
  60328. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60329. // return y in the World system
  60330. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60331. return tmpVect.y;
  60332. };
  60333. /**
  60334. * Returns a normalized vector (Vector3) orthogonal to the ground
  60335. * at the ground coordinates (x, z) expressed in the World system.
  60336. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60337. */
  60338. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60339. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60340. this.getNormalAtCoordinatesToRef(x, z, normal);
  60341. return normal;
  60342. };
  60343. /**
  60344. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60345. * at the ground coordinates (x, z) expressed in the World system.
  60346. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60347. * Returns the GroundMesh.
  60348. */
  60349. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60350. var world = this.getWorldMatrix();
  60351. var tmpMat = BABYLON.Tmp.Matrix[5];
  60352. world.invertToRef(tmpMat);
  60353. var tmpVect = BABYLON.Tmp.Vector3[8];
  60354. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60355. x = tmpVect.x;
  60356. z = tmpVect.z;
  60357. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60358. return this;
  60359. }
  60360. if (!this._heightQuads || this._heightQuads.length == 0) {
  60361. this._initHeightQuads();
  60362. this._computeHeightQuads();
  60363. }
  60364. var facet = this._getFacetAt(x, z);
  60365. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60366. return this;
  60367. };
  60368. /**
  60369. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60370. * if the ground has been updated.
  60371. * This can be used in the render loop.
  60372. * Returns the GroundMesh.
  60373. */
  60374. GroundMesh.prototype.updateCoordinateHeights = function () {
  60375. if (!this._heightQuads || this._heightQuads.length == 0) {
  60376. this._initHeightQuads();
  60377. }
  60378. this._computeHeightQuads();
  60379. return this;
  60380. };
  60381. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60382. GroundMesh.prototype._getFacetAt = function (x, z) {
  60383. // retrieve col and row from x, z coordinates in the ground local system
  60384. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60385. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60386. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60387. var facet;
  60388. if (z < quad.slope.x * x + quad.slope.y) {
  60389. facet = quad.facet1;
  60390. }
  60391. else {
  60392. facet = quad.facet2;
  60393. }
  60394. return facet;
  60395. };
  60396. // Creates and populates the heightMap array with "facet" elements :
  60397. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60398. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60399. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60400. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60401. // Returns the GroundMesh.
  60402. GroundMesh.prototype._initHeightQuads = function () {
  60403. var subdivisionsX = this._subdivisionsX;
  60404. var subdivisionsY = this._subdivisionsY;
  60405. this._heightQuads = new Array();
  60406. for (var row = 0; row < subdivisionsY; row++) {
  60407. for (var col = 0; col < subdivisionsX; col++) {
  60408. 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) };
  60409. this._heightQuads[row * subdivisionsX + col] = quad;
  60410. }
  60411. }
  60412. return this;
  60413. };
  60414. // Compute each quad element values and update the the heightMap array :
  60415. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60416. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60417. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60418. // Returns the GroundMesh.
  60419. GroundMesh.prototype._computeHeightQuads = function () {
  60420. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60421. if (!positions) {
  60422. return this;
  60423. }
  60424. var v1 = BABYLON.Tmp.Vector3[3];
  60425. var v2 = BABYLON.Tmp.Vector3[2];
  60426. var v3 = BABYLON.Tmp.Vector3[1];
  60427. var v4 = BABYLON.Tmp.Vector3[0];
  60428. var v1v2 = BABYLON.Tmp.Vector3[4];
  60429. var v1v3 = BABYLON.Tmp.Vector3[5];
  60430. var v1v4 = BABYLON.Tmp.Vector3[6];
  60431. var norm1 = BABYLON.Tmp.Vector3[7];
  60432. var norm2 = BABYLON.Tmp.Vector3[8];
  60433. var i = 0;
  60434. var j = 0;
  60435. var k = 0;
  60436. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60437. var h = 0;
  60438. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60439. var d2 = 0;
  60440. var subdivisionsX = this._subdivisionsX;
  60441. var subdivisionsY = this._subdivisionsY;
  60442. for (var row = 0; row < subdivisionsY; row++) {
  60443. for (var col = 0; col < subdivisionsX; col++) {
  60444. i = col * 3;
  60445. j = row * (subdivisionsX + 1) * 3;
  60446. k = (row + 1) * (subdivisionsX + 1) * 3;
  60447. v1.x = positions[j + i];
  60448. v1.y = positions[j + i + 1];
  60449. v1.z = positions[j + i + 2];
  60450. v2.x = positions[j + i + 3];
  60451. v2.y = positions[j + i + 4];
  60452. v2.z = positions[j + i + 5];
  60453. v3.x = positions[k + i];
  60454. v3.y = positions[k + i + 1];
  60455. v3.z = positions[k + i + 2];
  60456. v4.x = positions[k + i + 3];
  60457. v4.y = positions[k + i + 4];
  60458. v4.z = positions[k + i + 5];
  60459. // 2D slope V1V4
  60460. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60461. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60462. // facet equations :
  60463. // we compute each facet normal vector
  60464. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60465. // we compute the value d by applying the equation to v1 which belongs to the plane
  60466. // then we store the facet equation in a Vector4
  60467. v2.subtractToRef(v1, v1v2);
  60468. v3.subtractToRef(v1, v1v3);
  60469. v4.subtractToRef(v1, v1v4);
  60470. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60471. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60472. norm1.normalize();
  60473. norm2.normalize();
  60474. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60475. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60476. var quad = this._heightQuads[row * subdivisionsX + col];
  60477. quad.slope.copyFromFloats(cd, h);
  60478. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60479. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60480. }
  60481. }
  60482. return this;
  60483. };
  60484. GroundMesh.prototype.serialize = function (serializationObject) {
  60485. _super.prototype.serialize.call(this, serializationObject);
  60486. serializationObject.subdivisionsX = this._subdivisionsX;
  60487. serializationObject.subdivisionsY = this._subdivisionsY;
  60488. serializationObject.minX = this._minX;
  60489. serializationObject.maxX = this._maxX;
  60490. serializationObject.minZ = this._minZ;
  60491. serializationObject.maxZ = this._maxZ;
  60492. serializationObject.width = this._width;
  60493. serializationObject.height = this._height;
  60494. };
  60495. GroundMesh.Parse = function (parsedMesh, scene) {
  60496. var result = new GroundMesh(parsedMesh.name, scene);
  60497. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60498. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60499. result._minX = parsedMesh.minX;
  60500. result._maxX = parsedMesh.maxX;
  60501. result._minZ = parsedMesh.minZ;
  60502. result._maxZ = parsedMesh.maxZ;
  60503. result._width = parsedMesh.width;
  60504. result._height = parsedMesh.height;
  60505. return result;
  60506. };
  60507. return GroundMesh;
  60508. }(BABYLON.Mesh));
  60509. BABYLON.GroundMesh = GroundMesh;
  60510. })(BABYLON || (BABYLON = {}));
  60511. //# sourceMappingURL=babylon.groundMesh.js.map
  60512. var BABYLON;
  60513. (function (BABYLON) {
  60514. /**
  60515. * Creates an instance based on a source mesh.
  60516. */
  60517. var InstancedMesh = /** @class */ (function (_super) {
  60518. __extends(InstancedMesh, _super);
  60519. function InstancedMesh(name, source) {
  60520. var _this = _super.call(this, name, source.getScene()) || this;
  60521. source.instances.push(_this);
  60522. _this._sourceMesh = source;
  60523. _this.position.copyFrom(source.position);
  60524. _this.rotation.copyFrom(source.rotation);
  60525. _this.scaling.copyFrom(source.scaling);
  60526. if (source.rotationQuaternion) {
  60527. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60528. }
  60529. _this.infiniteDistance = source.infiniteDistance;
  60530. _this.setPivotMatrix(source.getPivotMatrix());
  60531. _this.refreshBoundingInfo();
  60532. _this._syncSubMeshes();
  60533. return _this;
  60534. }
  60535. /**
  60536. * Returns the string "InstancedMesh".
  60537. */
  60538. InstancedMesh.prototype.getClassName = function () {
  60539. return "InstancedMesh";
  60540. };
  60541. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60542. // Methods
  60543. get: function () {
  60544. return this._sourceMesh.receiveShadows;
  60545. },
  60546. enumerable: true,
  60547. configurable: true
  60548. });
  60549. Object.defineProperty(InstancedMesh.prototype, "material", {
  60550. get: function () {
  60551. return this._sourceMesh.material;
  60552. },
  60553. enumerable: true,
  60554. configurable: true
  60555. });
  60556. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60557. get: function () {
  60558. return this._sourceMesh.visibility;
  60559. },
  60560. enumerable: true,
  60561. configurable: true
  60562. });
  60563. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60564. get: function () {
  60565. return this._sourceMesh.skeleton;
  60566. },
  60567. enumerable: true,
  60568. configurable: true
  60569. });
  60570. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60571. get: function () {
  60572. return this._sourceMesh.renderingGroupId;
  60573. },
  60574. set: function (value) {
  60575. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60576. return;
  60577. }
  60578. //no-op with warning
  60579. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60580. },
  60581. enumerable: true,
  60582. configurable: true
  60583. });
  60584. /**
  60585. * Returns the total number of vertices (integer).
  60586. */
  60587. InstancedMesh.prototype.getTotalVertices = function () {
  60588. return this._sourceMesh.getTotalVertices();
  60589. };
  60590. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60591. get: function () {
  60592. return this._sourceMesh;
  60593. },
  60594. enumerable: true,
  60595. configurable: true
  60596. });
  60597. /**
  60598. * Is this node ready to be used/rendered
  60599. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60600. * @return {boolean} is it ready
  60601. */
  60602. InstancedMesh.prototype.isReady = function (completeCheck) {
  60603. if (completeCheck === void 0) { completeCheck = false; }
  60604. return this._sourceMesh.isReady(completeCheck, true);
  60605. };
  60606. /**
  60607. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60608. */
  60609. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60610. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60611. };
  60612. /**
  60613. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60614. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60615. * The `data` are either a numeric array either a Float32Array.
  60616. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60617. * 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).
  60618. * Note that a new underlying VertexBuffer object is created each call.
  60619. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60620. *
  60621. * Possible `kind` values :
  60622. * - BABYLON.VertexBuffer.PositionKind
  60623. * - BABYLON.VertexBuffer.UVKind
  60624. * - BABYLON.VertexBuffer.UV2Kind
  60625. * - BABYLON.VertexBuffer.UV3Kind
  60626. * - BABYLON.VertexBuffer.UV4Kind
  60627. * - BABYLON.VertexBuffer.UV5Kind
  60628. * - BABYLON.VertexBuffer.UV6Kind
  60629. * - BABYLON.VertexBuffer.ColorKind
  60630. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60631. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60632. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60633. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60634. *
  60635. * Returns the Mesh.
  60636. */
  60637. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60638. if (this.sourceMesh) {
  60639. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60640. }
  60641. return this.sourceMesh;
  60642. };
  60643. /**
  60644. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60645. * If the mesh has no geometry, it is simply returned as it is.
  60646. * The `data` are either a numeric array either a Float32Array.
  60647. * No new underlying VertexBuffer object is created.
  60648. * 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.
  60649. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60650. *
  60651. * Possible `kind` values :
  60652. * - BABYLON.VertexBuffer.PositionKind
  60653. * - BABYLON.VertexBuffer.UVKind
  60654. * - BABYLON.VertexBuffer.UV2Kind
  60655. * - BABYLON.VertexBuffer.UV3Kind
  60656. * - BABYLON.VertexBuffer.UV4Kind
  60657. * - BABYLON.VertexBuffer.UV5Kind
  60658. * - BABYLON.VertexBuffer.UV6Kind
  60659. * - BABYLON.VertexBuffer.ColorKind
  60660. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60661. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60662. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60663. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60664. *
  60665. * Returns the Mesh.
  60666. */
  60667. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60668. if (this.sourceMesh) {
  60669. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60670. }
  60671. return this.sourceMesh;
  60672. };
  60673. /**
  60674. * Sets the mesh indices.
  60675. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60676. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60677. * This method creates a new index buffer each call.
  60678. * Returns the Mesh.
  60679. */
  60680. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60681. if (totalVertices === void 0) { totalVertices = null; }
  60682. if (this.sourceMesh) {
  60683. this.sourceMesh.setIndices(indices, totalVertices);
  60684. }
  60685. return this.sourceMesh;
  60686. };
  60687. /**
  60688. * Boolean : True if the mesh owns the requested kind of data.
  60689. */
  60690. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60691. return this._sourceMesh.isVerticesDataPresent(kind);
  60692. };
  60693. /**
  60694. * Returns an array of indices (IndicesArray).
  60695. */
  60696. InstancedMesh.prototype.getIndices = function () {
  60697. return this._sourceMesh.getIndices();
  60698. };
  60699. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60700. get: function () {
  60701. return this._sourceMesh._positions;
  60702. },
  60703. enumerable: true,
  60704. configurable: true
  60705. });
  60706. /**
  60707. * Sets a new updated BoundingInfo to the mesh.
  60708. * Returns the mesh.
  60709. */
  60710. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60711. var meshBB = this._sourceMesh.getBoundingInfo();
  60712. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60713. this._updateBoundingInfo();
  60714. return this;
  60715. };
  60716. InstancedMesh.prototype._preActivate = function () {
  60717. if (this._currentLOD) {
  60718. this._currentLOD._preActivate();
  60719. }
  60720. return this;
  60721. };
  60722. InstancedMesh.prototype._activate = function (renderId) {
  60723. if (this._currentLOD) {
  60724. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60725. }
  60726. return this;
  60727. };
  60728. /**
  60729. * Returns the current associated LOD AbstractMesh.
  60730. */
  60731. InstancedMesh.prototype.getLOD = function (camera) {
  60732. if (!camera) {
  60733. return this;
  60734. }
  60735. var boundingInfo = this.getBoundingInfo();
  60736. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60737. if (this._currentLOD === this.sourceMesh) {
  60738. return this;
  60739. }
  60740. return this._currentLOD;
  60741. };
  60742. InstancedMesh.prototype._syncSubMeshes = function () {
  60743. this.releaseSubMeshes();
  60744. if (this._sourceMesh.subMeshes) {
  60745. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60746. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60747. }
  60748. }
  60749. return this;
  60750. };
  60751. InstancedMesh.prototype._generatePointsArray = function () {
  60752. return this._sourceMesh._generatePointsArray();
  60753. };
  60754. /**
  60755. * Creates a new InstancedMesh from the current mesh.
  60756. * - name (string) : the cloned mesh name
  60757. * - newParent (optional Node) : the optional Node to parent the clone to.
  60758. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60759. *
  60760. * Returns the clone.
  60761. */
  60762. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60763. var result = this._sourceMesh.createInstance(name);
  60764. // Deep copy
  60765. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60766. // Bounding info
  60767. this.refreshBoundingInfo();
  60768. // Parent
  60769. if (newParent) {
  60770. result.parent = newParent;
  60771. }
  60772. if (!doNotCloneChildren) {
  60773. // Children
  60774. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60775. var mesh = this.getScene().meshes[index];
  60776. if (mesh.parent === this) {
  60777. mesh.clone(mesh.name, result);
  60778. }
  60779. }
  60780. }
  60781. result.computeWorldMatrix(true);
  60782. return result;
  60783. };
  60784. /**
  60785. * Disposes the InstancedMesh.
  60786. * Returns nothing.
  60787. */
  60788. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60789. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60790. // Remove from mesh
  60791. var index = this._sourceMesh.instances.indexOf(this);
  60792. this._sourceMesh.instances.splice(index, 1);
  60793. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60794. };
  60795. return InstancedMesh;
  60796. }(BABYLON.AbstractMesh));
  60797. BABYLON.InstancedMesh = InstancedMesh;
  60798. })(BABYLON || (BABYLON = {}));
  60799. //# sourceMappingURL=babylon.instancedMesh.js.map
  60800. var BABYLON;
  60801. (function (BABYLON) {
  60802. var LinesMesh = /** @class */ (function (_super) {
  60803. __extends(LinesMesh, _super);
  60804. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60805. if (scene === void 0) { scene = null; }
  60806. if (parent === void 0) { parent = null; }
  60807. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60808. _this.useVertexColor = useVertexColor;
  60809. _this.useVertexAlpha = useVertexAlpha;
  60810. _this.color = new BABYLON.Color3(1, 1, 1);
  60811. _this.alpha = 1;
  60812. if (source) {
  60813. _this.color = source.color.clone();
  60814. _this.alpha = source.alpha;
  60815. _this.useVertexColor = source.useVertexColor;
  60816. _this.useVertexAlpha = source.useVertexAlpha;
  60817. }
  60818. _this._intersectionThreshold = 0.1;
  60819. var defines = [];
  60820. var options = {
  60821. attributes: [BABYLON.VertexBuffer.PositionKind],
  60822. uniforms: ["world", "viewProjection"],
  60823. needAlphaBlending: true,
  60824. defines: defines
  60825. };
  60826. if (useVertexAlpha === false) {
  60827. options.needAlphaBlending = false;
  60828. }
  60829. if (!useVertexColor) {
  60830. options.uniforms.push("color");
  60831. }
  60832. else {
  60833. options.defines.push("#define VERTEXCOLOR");
  60834. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60835. }
  60836. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60837. return _this;
  60838. }
  60839. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60840. /**
  60841. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60842. * This margin is expressed in world space coordinates, so its value may vary.
  60843. * Default value is 0.1
  60844. * @returns the intersection Threshold value.
  60845. */
  60846. get: function () {
  60847. return this._intersectionThreshold;
  60848. },
  60849. /**
  60850. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60851. * This margin is expressed in world space coordinates, so its value may vary.
  60852. * @param value the new threshold to apply
  60853. */
  60854. set: function (value) {
  60855. if (this._intersectionThreshold === value) {
  60856. return;
  60857. }
  60858. this._intersectionThreshold = value;
  60859. if (this.geometry) {
  60860. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60861. }
  60862. },
  60863. enumerable: true,
  60864. configurable: true
  60865. });
  60866. /**
  60867. * Returns the string "LineMesh"
  60868. */
  60869. LinesMesh.prototype.getClassName = function () {
  60870. return "LinesMesh";
  60871. };
  60872. Object.defineProperty(LinesMesh.prototype, "material", {
  60873. get: function () {
  60874. return this._colorShader;
  60875. },
  60876. set: function (value) {
  60877. // Do nothing
  60878. },
  60879. enumerable: true,
  60880. configurable: true
  60881. });
  60882. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60883. get: function () {
  60884. return false;
  60885. },
  60886. enumerable: true,
  60887. configurable: true
  60888. });
  60889. LinesMesh.prototype.createInstance = function (name) {
  60890. throw new Error("LinesMeshes do not support createInstance.");
  60891. };
  60892. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60893. if (!this._geometry) {
  60894. return this;
  60895. }
  60896. // VBOs
  60897. this._geometry._bind(this._colorShader.getEffect());
  60898. // Color
  60899. if (!this.useVertexColor) {
  60900. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60901. }
  60902. return this;
  60903. };
  60904. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60905. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60906. return this;
  60907. }
  60908. var engine = this.getScene().getEngine();
  60909. // Draw order
  60910. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60911. return this;
  60912. };
  60913. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60914. this._colorShader.dispose();
  60915. _super.prototype.dispose.call(this, doNotRecurse);
  60916. };
  60917. /**
  60918. * Returns a new LineMesh object cloned from the current one.
  60919. */
  60920. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60921. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60922. };
  60923. return LinesMesh;
  60924. }(BABYLON.Mesh));
  60925. BABYLON.LinesMesh = LinesMesh;
  60926. })(BABYLON || (BABYLON = {}));
  60927. //# sourceMappingURL=babylon.linesMesh.js.map
  60928. var BABYLON;
  60929. (function (BABYLON) {
  60930. /**
  60931. * Class containing static functions to help procedurally build meshes
  60932. */
  60933. var MeshBuilder = /** @class */ (function () {
  60934. function MeshBuilder() {
  60935. }
  60936. MeshBuilder.updateSideOrientation = function (orientation) {
  60937. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60938. return BABYLON.Mesh.DOUBLESIDE;
  60939. }
  60940. if (orientation === undefined || orientation === null) {
  60941. return BABYLON.Mesh.FRONTSIDE;
  60942. }
  60943. return orientation;
  60944. };
  60945. /**
  60946. * Creates a box mesh
  60947. * * The parameter `size` sets the size (float) of each box side (default 1)
  60948. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60949. * * 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)
  60950. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60951. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60952. * * 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
  60953. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60954. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60955. * @param name defines the name of the mesh
  60956. * @param options defines the options used to create the mesh
  60957. * @param scene defines the hosting scene
  60958. * @returns the box mesh
  60959. */
  60960. MeshBuilder.CreateBox = function (name, options, scene) {
  60961. if (scene === void 0) { scene = null; }
  60962. var box = new BABYLON.Mesh(name, scene);
  60963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60964. box._originalBuilderSideOrientation = options.sideOrientation;
  60965. var vertexData = BABYLON.VertexData.CreateBox(options);
  60966. vertexData.applyToMesh(box, options.updatable);
  60967. return box;
  60968. };
  60969. /**
  60970. * Creates a sphere mesh
  60971. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60972. * * 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`)
  60973. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60974. * * 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
  60975. * * 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)
  60976. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60977. * * 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
  60978. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60979. * @param name defines the name of the mesh
  60980. * @param options defines the options used to create the mesh
  60981. * @param scene defines the hosting scene
  60982. * @returns the sphere mesh
  60983. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60984. */
  60985. MeshBuilder.CreateSphere = function (name, options, scene) {
  60986. var sphere = new BABYLON.Mesh(name, scene);
  60987. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60988. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60989. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60990. vertexData.applyToMesh(sphere, options.updatable);
  60991. return sphere;
  60992. };
  60993. /**
  60994. * Creates a plane polygonal mesh. By default, this is a disc
  60995. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60996. * * 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
  60997. * * 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
  60998. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60999. * * 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
  61000. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61001. * @param name defines the name of the mesh
  61002. * @param options defines the options used to create the mesh
  61003. * @param scene defines the hosting scene
  61004. * @returns the plane polygonal mesh
  61005. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61006. */
  61007. MeshBuilder.CreateDisc = function (name, options, scene) {
  61008. if (scene === void 0) { scene = null; }
  61009. var disc = new BABYLON.Mesh(name, scene);
  61010. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61011. disc._originalBuilderSideOrientation = options.sideOrientation;
  61012. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61013. vertexData.applyToMesh(disc, options.updatable);
  61014. return disc;
  61015. };
  61016. /**
  61017. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61018. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61019. * * 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`)
  61020. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61021. * * 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
  61022. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61023. * * 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
  61024. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61025. * @param name defines the name of the mesh
  61026. * @param options defines the options used to create the mesh
  61027. * @param scene defines the hosting scene
  61028. * @returns the icosahedron mesh
  61029. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61030. */
  61031. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61032. var sphere = new BABYLON.Mesh(name, scene);
  61033. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61034. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61035. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61036. vertexData.applyToMesh(sphere, options.updatable);
  61037. return sphere;
  61038. };
  61039. ;
  61040. /**
  61041. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61042. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61043. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61044. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61045. * * 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
  61046. * * 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
  61047. * * 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
  61048. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61049. * * 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
  61050. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61051. * * 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
  61052. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61053. * * 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
  61054. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61055. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61056. * @param name defines the name of the mesh
  61057. * @param options defines the options used to create the mesh
  61058. * @param scene defines the hosting scene
  61059. * @returns the ribbon mesh
  61060. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61061. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61062. */
  61063. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61064. if (scene === void 0) { scene = null; }
  61065. var pathArray = options.pathArray;
  61066. var closeArray = options.closeArray;
  61067. var closePath = options.closePath;
  61068. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61069. var instance = options.instance;
  61070. var updatable = options.updatable;
  61071. if (instance) { // existing ribbon instance update
  61072. // positionFunction : ribbon case
  61073. // only pathArray and sideOrientation parameters are taken into account for positions update
  61074. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61075. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61076. var positionFunction = function (positions) {
  61077. var minlg = pathArray[0].length;
  61078. var i = 0;
  61079. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61080. for (var si = 1; si <= ns; si++) {
  61081. for (var p = 0; p < pathArray.length; p++) {
  61082. var path = pathArray[p];
  61083. var l = path.length;
  61084. minlg = (minlg < l) ? minlg : l;
  61085. var j = 0;
  61086. while (j < minlg) {
  61087. positions[i] = path[j].x;
  61088. positions[i + 1] = path[j].y;
  61089. positions[i + 2] = path[j].z;
  61090. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61091. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61092. }
  61093. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61094. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61095. }
  61096. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61097. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61098. }
  61099. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61100. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61101. }
  61102. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61103. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61104. }
  61105. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61106. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61107. }
  61108. j++;
  61109. i += 3;
  61110. }
  61111. if (instance._closePath) {
  61112. positions[i] = path[0].x;
  61113. positions[i + 1] = path[0].y;
  61114. positions[i + 2] = path[0].z;
  61115. i += 3;
  61116. }
  61117. }
  61118. }
  61119. };
  61120. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61121. positionFunction(positions);
  61122. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61123. instance._boundingInfo.update(instance._worldMatrix);
  61124. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61125. if (options.colors) {
  61126. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61127. for (var c = 0; c < options.colors.length; c++) {
  61128. colors[c * 4] = options.colors[c].r;
  61129. colors[c * 4 + 1] = options.colors[c].g;
  61130. colors[c * 4 + 2] = options.colors[c].b;
  61131. colors[c * 4 + 3] = options.colors[c].a;
  61132. }
  61133. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61134. }
  61135. if (options.uvs) {
  61136. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61137. for (var i = 0; i < options.uvs.length; i++) {
  61138. uvs[i * 2] = options.uvs[i].x;
  61139. uvs[i * 2 + 1] = options.uvs[i].y;
  61140. }
  61141. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61142. }
  61143. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61144. var indices = instance.getIndices();
  61145. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61146. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61147. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61148. if (instance._closePath) {
  61149. var indexFirst = 0;
  61150. var indexLast = 0;
  61151. for (var p = 0; p < pathArray.length; p++) {
  61152. indexFirst = instance._idx[p] * 3;
  61153. if (p + 1 < pathArray.length) {
  61154. indexLast = (instance._idx[p + 1] - 1) * 3;
  61155. }
  61156. else {
  61157. indexLast = normals.length - 3;
  61158. }
  61159. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61160. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61161. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61162. normals[indexLast] = normals[indexFirst];
  61163. normals[indexLast + 1] = normals[indexFirst + 1];
  61164. normals[indexLast + 2] = normals[indexFirst + 2];
  61165. }
  61166. }
  61167. if (!(instance.areNormalsFrozen)) {
  61168. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61169. }
  61170. }
  61171. return instance;
  61172. }
  61173. else { // new ribbon creation
  61174. var ribbon = new BABYLON.Mesh(name, scene);
  61175. ribbon._originalBuilderSideOrientation = sideOrientation;
  61176. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61177. if (closePath) {
  61178. ribbon._idx = vertexData._idx;
  61179. }
  61180. ribbon._closePath = closePath;
  61181. ribbon._closeArray = closeArray;
  61182. vertexData.applyToMesh(ribbon, updatable);
  61183. return ribbon;
  61184. }
  61185. };
  61186. /**
  61187. * Creates a cylinder or a cone mesh
  61188. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61189. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61190. * * 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.
  61191. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61192. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61193. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61194. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61195. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61196. * * 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).
  61197. * * 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
  61198. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61199. * * 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
  61200. * * 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.
  61201. * * If `enclose` is false, a ring surface is one element.
  61202. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61203. * * 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
  61204. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61205. * * 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
  61206. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61207. * @param name defines the name of the mesh
  61208. * @param options defines the options used to create the mesh
  61209. * @param scene defines the hosting scene
  61210. * @returns the cylinder mesh
  61211. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61212. */
  61213. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61214. var cylinder = new BABYLON.Mesh(name, scene);
  61215. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61216. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61217. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61218. vertexData.applyToMesh(cylinder, options.updatable);
  61219. return cylinder;
  61220. };
  61221. /**
  61222. * Creates a torus mesh
  61223. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61224. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61225. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61226. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61227. * * 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
  61228. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61229. * @param name defines the name of the mesh
  61230. * @param options defines the options used to create the mesh
  61231. * @param scene defines the hosting scene
  61232. * @returns the torus mesh
  61233. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61234. */
  61235. MeshBuilder.CreateTorus = function (name, options, scene) {
  61236. var torus = new BABYLON.Mesh(name, scene);
  61237. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61238. torus._originalBuilderSideOrientation = options.sideOrientation;
  61239. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61240. vertexData.applyToMesh(torus, options.updatable);
  61241. return torus;
  61242. };
  61243. /**
  61244. * Creates a torus knot mesh
  61245. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61246. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61247. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61248. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61249. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61250. * * 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
  61251. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61252. * @param name defines the name of the mesh
  61253. * @param options defines the options used to create the mesh
  61254. * @param scene defines the hosting scene
  61255. * @returns the torus knot mesh
  61256. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61257. */
  61258. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61259. var torusKnot = new BABYLON.Mesh(name, scene);
  61260. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61261. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61262. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61263. vertexData.applyToMesh(torusKnot, options.updatable);
  61264. return torusKnot;
  61265. };
  61266. /**
  61267. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61268. * * 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
  61269. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61270. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61271. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61272. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61273. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61274. * * 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
  61275. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61276. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61277. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61278. * @param name defines the name of the new line system
  61279. * @param options defines the options used to create the line system
  61280. * @param scene defines the hosting scene
  61281. * @returns a new line system mesh
  61282. */
  61283. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61284. var instance = options.instance;
  61285. var lines = options.lines;
  61286. var colors = options.colors;
  61287. if (instance) { // lines update
  61288. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61289. var vertexColor;
  61290. var lineColors;
  61291. if (colors) {
  61292. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61293. }
  61294. var i = 0;
  61295. var c = 0;
  61296. for (var l = 0; l < lines.length; l++) {
  61297. var points = lines[l];
  61298. for (var p = 0; p < points.length; p++) {
  61299. positions[i] = points[p].x;
  61300. positions[i + 1] = points[p].y;
  61301. positions[i + 2] = points[p].z;
  61302. if (colors && vertexColor) {
  61303. lineColors = colors[l];
  61304. vertexColor[c] = lineColors[p].r;
  61305. vertexColor[c + 1] = lineColors[p].g;
  61306. vertexColor[c + 2] = lineColors[p].b;
  61307. vertexColor[c + 3] = lineColors[p].a;
  61308. c += 4;
  61309. }
  61310. i += 3;
  61311. }
  61312. }
  61313. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61314. if (colors && vertexColor) {
  61315. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61316. }
  61317. return instance;
  61318. }
  61319. // line system creation
  61320. var useVertexColor = (colors) ? true : false;
  61321. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61322. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61323. vertexData.applyToMesh(lineSystem, options.updatable);
  61324. return lineSystem;
  61325. };
  61326. /**
  61327. * Creates a line mesh
  61328. * 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
  61329. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61330. * * The parameter `points` is an array successive Vector3
  61331. * * 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
  61332. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61333. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61334. * * When updating an instance, remember that only point positions can change, not the number of points
  61335. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61336. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61337. * @param name defines the name of the new line system
  61338. * @param options defines the options used to create the line system
  61339. * @param scene defines the hosting scene
  61340. * @returns a new line mesh
  61341. */
  61342. MeshBuilder.CreateLines = function (name, options, scene) {
  61343. if (scene === void 0) { scene = null; }
  61344. var colors = (options.colors) ? [options.colors] : null;
  61345. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61346. return lines;
  61347. };
  61348. /**
  61349. * Creates a dashed line mesh
  61350. * * 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
  61351. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61352. * * The parameter `points` is an array successive Vector3
  61353. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61354. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61355. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61356. * * 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
  61357. * * When updating an instance, remember that only point positions can change, not the number of points
  61358. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61359. * @param name defines the name of the mesh
  61360. * @param options defines the options used to create the mesh
  61361. * @param scene defines the hosting scene
  61362. * @returns the dashed line mesh
  61363. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61364. */
  61365. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61366. if (scene === void 0) { scene = null; }
  61367. var points = options.points;
  61368. var instance = options.instance;
  61369. var gapSize = options.gapSize || 1;
  61370. var dashSize = options.dashSize || 3;
  61371. if (instance) { // dashed lines update
  61372. var positionFunction = function (positions) {
  61373. var curvect = BABYLON.Vector3.Zero();
  61374. var nbSeg = positions.length / 6;
  61375. var lg = 0;
  61376. var nb = 0;
  61377. var shft = 0;
  61378. var dashshft = 0;
  61379. var curshft = 0;
  61380. var p = 0;
  61381. var i = 0;
  61382. var j = 0;
  61383. for (i = 0; i < points.length - 1; i++) {
  61384. points[i + 1].subtractToRef(points[i], curvect);
  61385. lg += curvect.length();
  61386. }
  61387. shft = lg / nbSeg;
  61388. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61389. for (i = 0; i < points.length - 1; i++) {
  61390. points[i + 1].subtractToRef(points[i], curvect);
  61391. nb = Math.floor(curvect.length() / shft);
  61392. curvect.normalize();
  61393. j = 0;
  61394. while (j < nb && p < positions.length) {
  61395. curshft = shft * j;
  61396. positions[p] = points[i].x + curshft * curvect.x;
  61397. positions[p + 1] = points[i].y + curshft * curvect.y;
  61398. positions[p + 2] = points[i].z + curshft * curvect.z;
  61399. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61400. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61401. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61402. p += 6;
  61403. j++;
  61404. }
  61405. }
  61406. while (p < positions.length) {
  61407. positions[p] = points[i].x;
  61408. positions[p + 1] = points[i].y;
  61409. positions[p + 2] = points[i].z;
  61410. p += 3;
  61411. }
  61412. };
  61413. instance.updateMeshPositions(positionFunction, false);
  61414. return instance;
  61415. }
  61416. // dashed lines creation
  61417. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61418. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61419. vertexData.applyToMesh(dashedLines, options.updatable);
  61420. dashedLines.dashSize = dashSize;
  61421. dashedLines.gapSize = gapSize;
  61422. return dashedLines;
  61423. };
  61424. /**
  61425. * 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.
  61426. * * 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.
  61427. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61428. * * 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.
  61429. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61430. * * 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
  61431. * * 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
  61432. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61433. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61434. * * 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
  61435. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61436. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61437. * @param name defines the name of the mesh
  61438. * @param options defines the options used to create the mesh
  61439. * @param scene defines the hosting scene
  61440. * @returns the extruded shape mesh
  61441. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61442. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61443. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61444. */
  61445. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61446. if (scene === void 0) { scene = null; }
  61447. var path = options.path;
  61448. var shape = options.shape;
  61449. var scale = options.scale || 1;
  61450. var rotation = options.rotation || 0;
  61451. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61452. var updatable = options.updatable;
  61453. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61454. var instance = options.instance || null;
  61455. var invertUV = options.invertUV || false;
  61456. 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);
  61457. };
  61458. /**
  61459. * Creates an custom extruded shape mesh.
  61460. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61461. * * 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.
  61462. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61463. * * 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
  61464. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61465. * * 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
  61466. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61467. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61468. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61469. * * 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
  61470. * * 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
  61471. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61472. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61473. * * 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
  61474. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61475. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61476. * @param name defines the name of the mesh
  61477. * @param options defines the options used to create the mesh
  61478. * @param scene defines the hosting scene
  61479. * @returns the custom extruded shape mesh
  61480. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61481. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61482. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61483. */
  61484. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61485. var path = options.path;
  61486. var shape = options.shape;
  61487. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61488. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61489. var ribbonCloseArray = options.ribbonCloseArray || false;
  61490. var ribbonClosePath = options.ribbonClosePath || false;
  61491. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61492. var updatable = options.updatable;
  61493. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61494. var instance = options.instance;
  61495. var invertUV = options.invertUV || false;
  61496. 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);
  61497. };
  61498. /**
  61499. * Creates lathe mesh.
  61500. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61501. * * 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
  61502. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61503. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61504. * * 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
  61505. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61506. * * 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
  61507. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61508. * * 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
  61509. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61510. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61511. * @param name defines the name of the mesh
  61512. * @param options defines the options used to create the mesh
  61513. * @param scene defines the hosting scene
  61514. * @returns the lathe mesh
  61515. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61516. */
  61517. MeshBuilder.CreateLathe = function (name, options, scene) {
  61518. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61519. var closed = (options.closed === undefined) ? true : options.closed;
  61520. var shape = options.shape;
  61521. var radius = options.radius || 1;
  61522. var tessellation = options.tessellation || 64;
  61523. var updatable = options.updatable;
  61524. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61525. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61526. var pi2 = Math.PI * 2;
  61527. var paths = new Array();
  61528. var invertUV = options.invertUV || false;
  61529. var i = 0;
  61530. var p = 0;
  61531. var step = pi2 / tessellation * arc;
  61532. var rotated;
  61533. var path = new Array();
  61534. for (i = 0; i <= tessellation; i++) {
  61535. var path = [];
  61536. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61537. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61538. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61539. }
  61540. for (p = 0; p < shape.length; p++) {
  61541. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61542. path.push(rotated);
  61543. }
  61544. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61545. 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));
  61546. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61547. }
  61548. paths.push(path);
  61549. }
  61550. // lathe ribbon
  61551. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61552. return lathe;
  61553. };
  61554. /**
  61555. * Creates a plane mesh
  61556. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61557. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61558. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61559. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61560. * * 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
  61561. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61562. * @param name defines the name of the mesh
  61563. * @param options defines the options used to create the mesh
  61564. * @param scene defines the hosting scene
  61565. * @returns the plane mesh
  61566. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61567. */
  61568. MeshBuilder.CreatePlane = function (name, options, scene) {
  61569. var plane = new BABYLON.Mesh(name, scene);
  61570. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61571. plane._originalBuilderSideOrientation = options.sideOrientation;
  61572. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61573. vertexData.applyToMesh(plane, options.updatable);
  61574. if (options.sourcePlane) {
  61575. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61576. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61577. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61578. plane.rotate(vectorProduct, product);
  61579. }
  61580. return plane;
  61581. };
  61582. /**
  61583. * Creates a ground mesh
  61584. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61585. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61586. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61587. * @param name defines the name of the mesh
  61588. * @param options defines the options used to create the mesh
  61589. * @param scene defines the hosting scene
  61590. * @returns the ground mesh
  61591. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61592. */
  61593. MeshBuilder.CreateGround = function (name, options, scene) {
  61594. var ground = new BABYLON.GroundMesh(name, scene);
  61595. ground._setReady(false);
  61596. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61597. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61598. ground._width = options.width || 1;
  61599. ground._height = options.height || 1;
  61600. ground._maxX = ground._width / 2;
  61601. ground._maxZ = ground._height / 2;
  61602. ground._minX = -ground._maxX;
  61603. ground._minZ = -ground._maxZ;
  61604. var vertexData = BABYLON.VertexData.CreateGround(options);
  61605. vertexData.applyToMesh(ground, options.updatable);
  61606. ground._setReady(true);
  61607. return ground;
  61608. };
  61609. /**
  61610. * Creates a tiled ground mesh
  61611. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61612. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61613. * * 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
  61614. * * 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
  61615. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61616. * @param name defines the name of the mesh
  61617. * @param options defines the options used to create the mesh
  61618. * @param scene defines the hosting scene
  61619. * @returns the tiled ground mesh
  61620. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61621. */
  61622. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61623. var tiledGround = new BABYLON.Mesh(name, scene);
  61624. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61625. vertexData.applyToMesh(tiledGround, options.updatable);
  61626. return tiledGround;
  61627. };
  61628. /**
  61629. * Creates a ground mesh from a height map
  61630. * * The parameter `url` sets the URL of the height map image resource.
  61631. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61632. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61633. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61634. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61635. * * 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.
  61636. * * 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).
  61637. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61638. * @param name defines the name of the mesh
  61639. * @param url defines the url to the height map
  61640. * @param options defines the options used to create the mesh
  61641. * @param scene defines the hosting scene
  61642. * @returns the ground mesh
  61643. * @see http://doc.babylonjs.com/babylon101/height_map
  61644. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61645. */
  61646. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61647. var width = options.width || 10.0;
  61648. var height = options.height || 10.0;
  61649. var subdivisions = options.subdivisions || 1 | 0;
  61650. var minHeight = options.minHeight || 0.0;
  61651. var maxHeight = options.maxHeight || 1.0;
  61652. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61653. var updatable = options.updatable;
  61654. var onReady = options.onReady;
  61655. var ground = new BABYLON.GroundMesh(name, scene);
  61656. ground._subdivisionsX = subdivisions;
  61657. ground._subdivisionsY = subdivisions;
  61658. ground._width = width;
  61659. ground._height = height;
  61660. ground._maxX = ground._width / 2.0;
  61661. ground._maxZ = ground._height / 2.0;
  61662. ground._minX = -ground._maxX;
  61663. ground._minZ = -ground._maxZ;
  61664. ground._setReady(false);
  61665. var onload = function (img) {
  61666. // Getting height map data
  61667. var canvas = document.createElement("canvas");
  61668. var context = canvas.getContext("2d");
  61669. if (!context) {
  61670. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61671. }
  61672. if (scene.isDisposed) {
  61673. return;
  61674. }
  61675. var bufferWidth = img.width;
  61676. var bufferHeight = img.height;
  61677. canvas.width = bufferWidth;
  61678. canvas.height = bufferHeight;
  61679. context.drawImage(img, 0, 0);
  61680. // Create VertexData from map data
  61681. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61682. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61683. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61684. width: width, height: height,
  61685. subdivisions: subdivisions,
  61686. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61687. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61688. });
  61689. vertexData.applyToMesh(ground, updatable);
  61690. //execute ready callback, if set
  61691. if (onReady) {
  61692. onReady(ground);
  61693. }
  61694. ground._setReady(true);
  61695. };
  61696. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61697. return ground;
  61698. };
  61699. /**
  61700. * Creates a polygon mesh
  61701. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61702. * * 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
  61703. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61704. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61705. * * 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)
  61706. * * Remember you can only change the shape positions, not their number when updating a polygon
  61707. * @param name defines the name of the mesh
  61708. * @param options defines the options used to create the mesh
  61709. * @param scene defines the hosting scene
  61710. * @returns the polygon mesh
  61711. */
  61712. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61713. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61714. var shape = options.shape;
  61715. var holes = options.holes || [];
  61716. var depth = options.depth || 0;
  61717. var contours = [];
  61718. var hole = [];
  61719. for (var i = 0; i < shape.length; i++) {
  61720. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61721. }
  61722. var epsilon = 0.00000001;
  61723. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61724. contours.pop();
  61725. }
  61726. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61727. for (var hNb = 0; hNb < holes.length; hNb++) {
  61728. hole = [];
  61729. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61730. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61731. }
  61732. polygonTriangulation.addHole(hole);
  61733. }
  61734. var polygon = polygonTriangulation.build(options.updatable, depth);
  61735. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61736. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61737. vertexData.applyToMesh(polygon, options.updatable);
  61738. return polygon;
  61739. };
  61740. ;
  61741. /**
  61742. * Creates an extruded polygon mesh, with depth in the Y direction.
  61743. * * 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)
  61744. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61745. * @param name defines the name of the mesh
  61746. * @param options defines the options used to create the mesh
  61747. * @param scene defines the hosting scene
  61748. * @returns the polygon mesh
  61749. */
  61750. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61751. return MeshBuilder.CreatePolygon(name, options, scene);
  61752. };
  61753. ;
  61754. /**
  61755. * Creates a tube mesh.
  61756. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61757. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61758. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61759. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61760. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61761. * * 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)
  61762. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61763. * * 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
  61764. * * 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
  61765. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61766. * * 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
  61767. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61768. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61769. * @param name defines the name of the mesh
  61770. * @param options defines the options used to create the mesh
  61771. * @param scene defines the hosting scene
  61772. * @returns the tube mesh
  61773. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61774. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61775. */
  61776. MeshBuilder.CreateTube = function (name, options, scene) {
  61777. var path = options.path;
  61778. var instance = options.instance;
  61779. var radius = 1.0;
  61780. if (instance) {
  61781. radius = instance.radius;
  61782. }
  61783. if (options.radius !== undefined) {
  61784. radius = options.radius;
  61785. }
  61786. ;
  61787. var tessellation = options.tessellation || 64 | 0;
  61788. var radiusFunction = options.radiusFunction || null;
  61789. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61790. var invertUV = options.invertUV || false;
  61791. var updatable = options.updatable;
  61792. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61793. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61794. // tube geometry
  61795. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61796. var tangents = path3D.getTangents();
  61797. var normals = path3D.getNormals();
  61798. var distances = path3D.getDistances();
  61799. var pi2 = Math.PI * 2;
  61800. var step = pi2 / tessellation * arc;
  61801. var returnRadius = function () { return radius; };
  61802. var radiusFunctionFinal = radiusFunction || returnRadius;
  61803. var circlePath;
  61804. var rad;
  61805. var normal;
  61806. var rotated;
  61807. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61808. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61809. for (var i = 0; i < path.length; i++) {
  61810. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61811. circlePath = Array(); // current circle array
  61812. normal = normals[i]; // current normal
  61813. for (var t = 0; t < tessellation; t++) {
  61814. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61815. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61816. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61817. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61818. circlePath[t] = rotated;
  61819. }
  61820. circlePaths[index] = circlePath;
  61821. index++;
  61822. }
  61823. // cap
  61824. var capPath = function (nbPoints, pathIndex) {
  61825. var pointCap = Array();
  61826. for (var i = 0; i < nbPoints; i++) {
  61827. pointCap.push(path[pathIndex]);
  61828. }
  61829. return pointCap;
  61830. };
  61831. switch (cap) {
  61832. case BABYLON.Mesh.NO_CAP:
  61833. break;
  61834. case BABYLON.Mesh.CAP_START:
  61835. circlePaths[0] = capPath(tessellation, 0);
  61836. circlePaths[1] = circlePaths[2].slice(0);
  61837. break;
  61838. case BABYLON.Mesh.CAP_END:
  61839. circlePaths[index] = circlePaths[index - 1].slice(0);
  61840. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61841. break;
  61842. case BABYLON.Mesh.CAP_ALL:
  61843. circlePaths[0] = capPath(tessellation, 0);
  61844. circlePaths[1] = circlePaths[2].slice(0);
  61845. circlePaths[index] = circlePaths[index - 1].slice(0);
  61846. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61847. break;
  61848. default:
  61849. break;
  61850. }
  61851. return circlePaths;
  61852. };
  61853. var path3D;
  61854. var pathArray;
  61855. if (instance) { // tube update
  61856. var arc = options.arc || instance.arc;
  61857. path3D = (instance.path3D).update(path);
  61858. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61859. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61860. instance.path3D = path3D;
  61861. instance.pathArray = pathArray;
  61862. instance.arc = arc;
  61863. instance.radius = radius;
  61864. return instance;
  61865. }
  61866. // tube creation
  61867. path3D = new BABYLON.Path3D(path);
  61868. var newPathArray = new Array();
  61869. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61870. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61871. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61872. tube.pathArray = pathArray;
  61873. tube.path3D = path3D;
  61874. tube.tessellation = tessellation;
  61875. tube.cap = cap;
  61876. tube.arc = options.arc;
  61877. tube.radius = radius;
  61878. return tube;
  61879. };
  61880. /**
  61881. * Creates a polyhedron mesh
  61882. * * 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
  61883. * * The parameter `size` (positive float, default 1) sets the polygon size
  61884. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61885. * * 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`
  61886. * * 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
  61887. * * 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)`)
  61888. * * 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
  61889. * * 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
  61890. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61891. * * 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
  61892. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61893. * @param name defines the name of the mesh
  61894. * @param options defines the options used to create the mesh
  61895. * @param scene defines the hosting scene
  61896. * @returns the polyhedron mesh
  61897. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61898. */
  61899. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61900. var polyhedron = new BABYLON.Mesh(name, scene);
  61901. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61902. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61903. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61904. vertexData.applyToMesh(polyhedron, options.updatable);
  61905. return polyhedron;
  61906. };
  61907. /**
  61908. * Creates a decal mesh.
  61909. * 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
  61910. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61911. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61912. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61913. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61914. * @param name defines the name of the mesh
  61915. * @param sourceMesh defines the mesh where the decal must be applied
  61916. * @param options defines the options used to create the mesh
  61917. * @param scene defines the hosting scene
  61918. * @returns the decal mesh
  61919. * @see http://doc.babylonjs.com/how_to/decals
  61920. */
  61921. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61922. var indices = sourceMesh.getIndices();
  61923. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61924. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61925. var position = options.position || BABYLON.Vector3.Zero();
  61926. var normal = options.normal || BABYLON.Vector3.Up();
  61927. var size = options.size || BABYLON.Vector3.One();
  61928. var angle = options.angle || 0;
  61929. // Getting correct rotation
  61930. if (!normal) {
  61931. var target = new BABYLON.Vector3(0, 0, 1);
  61932. var camera = sourceMesh.getScene().activeCamera;
  61933. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61934. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61935. }
  61936. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61937. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61938. var pitch = Math.atan2(normal.y, len);
  61939. // Matrix
  61940. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61941. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61942. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61943. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61944. var vertexData = new BABYLON.VertexData();
  61945. vertexData.indices = [];
  61946. vertexData.positions = [];
  61947. vertexData.normals = [];
  61948. vertexData.uvs = [];
  61949. var currentVertexDataIndex = 0;
  61950. var extractDecalVector3 = function (indexId) {
  61951. var result = new BABYLON.PositionNormalVertex();
  61952. if (!indices || !positions || !normals) {
  61953. return result;
  61954. }
  61955. var vertexId = indices[indexId];
  61956. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61957. // Send vector to decal local world
  61958. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61959. // Get normal
  61960. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61961. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61962. return result;
  61963. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61964. var clip = function (vertices, axis) {
  61965. if (vertices.length === 0) {
  61966. return vertices;
  61967. }
  61968. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61969. var clipVertices = function (v0, v1) {
  61970. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61971. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61972. };
  61973. var result = new Array();
  61974. for (var index = 0; index < vertices.length; index += 3) {
  61975. var v1Out;
  61976. var v2Out;
  61977. var v3Out;
  61978. var total = 0;
  61979. var nV1 = null;
  61980. var nV2 = null;
  61981. var nV3 = null;
  61982. var nV4 = null;
  61983. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61984. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61985. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61986. v1Out = d1 > 0;
  61987. v2Out = d2 > 0;
  61988. v3Out = d3 > 0;
  61989. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61990. switch (total) {
  61991. case 0:
  61992. result.push(vertices[index]);
  61993. result.push(vertices[index + 1]);
  61994. result.push(vertices[index + 2]);
  61995. break;
  61996. case 1:
  61997. if (v1Out) {
  61998. nV1 = vertices[index + 1];
  61999. nV2 = vertices[index + 2];
  62000. nV3 = clipVertices(vertices[index], nV1);
  62001. nV4 = clipVertices(vertices[index], nV2);
  62002. }
  62003. if (v2Out) {
  62004. nV1 = vertices[index];
  62005. nV2 = vertices[index + 2];
  62006. nV3 = clipVertices(vertices[index + 1], nV1);
  62007. nV4 = clipVertices(vertices[index + 1], nV2);
  62008. result.push(nV3);
  62009. result.push(nV2.clone());
  62010. result.push(nV1.clone());
  62011. result.push(nV2.clone());
  62012. result.push(nV3.clone());
  62013. result.push(nV4);
  62014. break;
  62015. }
  62016. if (v3Out) {
  62017. nV1 = vertices[index];
  62018. nV2 = vertices[index + 1];
  62019. nV3 = clipVertices(vertices[index + 2], nV1);
  62020. nV4 = clipVertices(vertices[index + 2], nV2);
  62021. }
  62022. if (nV1 && nV2 && nV3 && nV4) {
  62023. result.push(nV1.clone());
  62024. result.push(nV2.clone());
  62025. result.push(nV3);
  62026. result.push(nV4);
  62027. result.push(nV3.clone());
  62028. result.push(nV2.clone());
  62029. }
  62030. break;
  62031. case 2:
  62032. if (!v1Out) {
  62033. nV1 = vertices[index].clone();
  62034. nV2 = clipVertices(nV1, vertices[index + 1]);
  62035. nV3 = clipVertices(nV1, vertices[index + 2]);
  62036. result.push(nV1);
  62037. result.push(nV2);
  62038. result.push(nV3);
  62039. }
  62040. if (!v2Out) {
  62041. nV1 = vertices[index + 1].clone();
  62042. nV2 = clipVertices(nV1, vertices[index + 2]);
  62043. nV3 = clipVertices(nV1, vertices[index]);
  62044. result.push(nV1);
  62045. result.push(nV2);
  62046. result.push(nV3);
  62047. }
  62048. if (!v3Out) {
  62049. nV1 = vertices[index + 2].clone();
  62050. nV2 = clipVertices(nV1, vertices[index]);
  62051. nV3 = clipVertices(nV1, vertices[index + 1]);
  62052. result.push(nV1);
  62053. result.push(nV2);
  62054. result.push(nV3);
  62055. }
  62056. break;
  62057. case 3:
  62058. break;
  62059. }
  62060. }
  62061. return result;
  62062. };
  62063. for (var index = 0; index < indices.length; index += 3) {
  62064. var faceVertices = new Array();
  62065. faceVertices.push(extractDecalVector3(index));
  62066. faceVertices.push(extractDecalVector3(index + 1));
  62067. faceVertices.push(extractDecalVector3(index + 2));
  62068. // Clip
  62069. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62070. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62071. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62072. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62073. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62074. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62075. if (faceVertices.length === 0) {
  62076. continue;
  62077. }
  62078. // Add UVs and get back to world
  62079. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62080. var vertex = faceVertices[vIndex];
  62081. //TODO check for Int32Array | Uint32Array | Uint16Array
  62082. vertexData.indices.push(currentVertexDataIndex);
  62083. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62084. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62085. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62086. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62087. currentVertexDataIndex++;
  62088. }
  62089. }
  62090. // Return mesh
  62091. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62092. vertexData.applyToMesh(decal);
  62093. decal.position = position.clone();
  62094. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62095. return decal;
  62096. };
  62097. // Privates
  62098. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62099. // extrusion geometry
  62100. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62101. var tangents = path3D.getTangents();
  62102. var normals = path3D.getNormals();
  62103. var binormals = path3D.getBinormals();
  62104. var distances = path3D.getDistances();
  62105. var angle = 0;
  62106. var returnScale = function () { return scale !== null ? scale : 1; };
  62107. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62108. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62109. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62110. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62111. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62112. for (var i = 0; i < curve.length; i++) {
  62113. var shapePath = new Array();
  62114. var angleStep = rotate(i, distances[i]);
  62115. var scaleRatio = scl(i, distances[i]);
  62116. for (var p = 0; p < shape.length; p++) {
  62117. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62118. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62119. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62120. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62121. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62122. shapePath[p] = rotated;
  62123. }
  62124. shapePaths[index] = shapePath;
  62125. angle += angleStep;
  62126. index++;
  62127. }
  62128. // cap
  62129. var capPath = function (shapePath) {
  62130. var pointCap = Array();
  62131. var barycenter = BABYLON.Vector3.Zero();
  62132. var i;
  62133. for (i = 0; i < shapePath.length; i++) {
  62134. barycenter.addInPlace(shapePath[i]);
  62135. }
  62136. barycenter.scaleInPlace(1.0 / shapePath.length);
  62137. for (i = 0; i < shapePath.length; i++) {
  62138. pointCap.push(barycenter);
  62139. }
  62140. return pointCap;
  62141. };
  62142. switch (cap) {
  62143. case BABYLON.Mesh.NO_CAP:
  62144. break;
  62145. case BABYLON.Mesh.CAP_START:
  62146. shapePaths[0] = capPath(shapePaths[2]);
  62147. shapePaths[1] = shapePaths[2];
  62148. break;
  62149. case BABYLON.Mesh.CAP_END:
  62150. shapePaths[index] = shapePaths[index - 1];
  62151. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62152. break;
  62153. case BABYLON.Mesh.CAP_ALL:
  62154. shapePaths[0] = capPath(shapePaths[2]);
  62155. shapePaths[1] = shapePaths[2];
  62156. shapePaths[index] = shapePaths[index - 1];
  62157. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62158. break;
  62159. default:
  62160. break;
  62161. }
  62162. return shapePaths;
  62163. };
  62164. var path3D;
  62165. var pathArray;
  62166. if (instance) { // instance update
  62167. path3D = (instance.path3D).update(curve);
  62168. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62169. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62170. return instance;
  62171. }
  62172. // extruded shape creation
  62173. path3D = new BABYLON.Path3D(curve);
  62174. var newShapePaths = new Array();
  62175. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62176. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62177. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62178. extrudedGeneric.pathArray = pathArray;
  62179. extrudedGeneric.path3D = path3D;
  62180. extrudedGeneric.cap = cap;
  62181. return extrudedGeneric;
  62182. };
  62183. return MeshBuilder;
  62184. }());
  62185. BABYLON.MeshBuilder = MeshBuilder;
  62186. })(BABYLON || (BABYLON = {}));
  62187. //# sourceMappingURL=babylon.meshBuilder.js.map
  62188. var BABYLON;
  62189. (function (BABYLON) {
  62190. /**
  62191. * Draco compression (https://google.github.io/draco/)
  62192. *
  62193. * This class wraps the Draco module.
  62194. *
  62195. * **Encoder**
  62196. *
  62197. * The encoder is not currently implemented.
  62198. *
  62199. * **Decoder**
  62200. *
  62201. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62202. *
  62203. * To update the configuration, use the following code:
  62204. * ```javascript
  62205. * BABYLON.DracoCompression.Configuration = {
  62206. * decoder: {
  62207. * wasmUrl: "<url to the WebAssembly library>",
  62208. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62209. * fallbackUrl: "<url to the fallback JavaScript library>",
  62210. * }
  62211. * };
  62212. * ```
  62213. *
  62214. * 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.
  62215. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62216. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62217. *
  62218. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62219. * ```javascript
  62220. * var dracoCompression = new BABYLON.DracoCompression();
  62221. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62222. * [BABYLON.VertexBuffer.PositionKind]: 0
  62223. * });
  62224. * ```
  62225. *
  62226. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62227. */
  62228. var DracoCompression = /** @class */ (function () {
  62229. /**
  62230. * Constructor
  62231. */
  62232. function DracoCompression() {
  62233. }
  62234. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62235. /**
  62236. * Returns true if the decoder is available.
  62237. */
  62238. get: function () {
  62239. if (typeof DracoDecoderModule !== "undefined") {
  62240. return true;
  62241. }
  62242. var decoder = DracoCompression.Configuration.decoder;
  62243. if (decoder) {
  62244. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62245. return true;
  62246. }
  62247. if (decoder.fallbackUrl) {
  62248. return true;
  62249. }
  62250. }
  62251. return false;
  62252. },
  62253. enumerable: true,
  62254. configurable: true
  62255. });
  62256. /**
  62257. * Stop all async operations and release resources.
  62258. */
  62259. DracoCompression.prototype.dispose = function () {
  62260. };
  62261. /**
  62262. * Decode Draco compressed mesh data to vertex data.
  62263. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62264. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62265. * @returns A promise that resolves with the decoded vertex data
  62266. */
  62267. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62268. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62269. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62270. var module = wrappedModule.module;
  62271. var vertexData = new BABYLON.VertexData();
  62272. var buffer = new module.DecoderBuffer();
  62273. buffer.Init(dataView, dataView.byteLength);
  62274. var decoder = new module.Decoder();
  62275. var geometry;
  62276. var status;
  62277. try {
  62278. var type = decoder.GetEncodedGeometryType(buffer);
  62279. switch (type) {
  62280. case module.TRIANGULAR_MESH:
  62281. geometry = new module.Mesh();
  62282. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62283. break;
  62284. case module.POINT_CLOUD:
  62285. geometry = new module.PointCloud();
  62286. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62287. break;
  62288. default:
  62289. throw new Error("Invalid geometry type " + type);
  62290. }
  62291. if (!status.ok() || !geometry.ptr) {
  62292. throw new Error(status.error_msg());
  62293. }
  62294. var numPoints = geometry.num_points();
  62295. if (type === module.TRIANGULAR_MESH) {
  62296. var numFaces = geometry.num_faces();
  62297. var faceIndices = new module.DracoInt32Array();
  62298. try {
  62299. var indices = new Uint32Array(numFaces * 3);
  62300. for (var i = 0; i < numFaces; i++) {
  62301. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62302. var offset = i * 3;
  62303. indices[offset + 0] = faceIndices.GetValue(0);
  62304. indices[offset + 1] = faceIndices.GetValue(1);
  62305. indices[offset + 2] = faceIndices.GetValue(2);
  62306. }
  62307. vertexData.indices = indices;
  62308. }
  62309. finally {
  62310. module.destroy(faceIndices);
  62311. }
  62312. }
  62313. for (var kind in attributes) {
  62314. var uniqueId = attributes[kind];
  62315. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62316. var dracoData = new module.DracoFloat32Array();
  62317. try {
  62318. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62319. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62320. for (var i = 0; i < babylonData.length; i++) {
  62321. babylonData[i] = dracoData.GetValue(i);
  62322. }
  62323. vertexData.set(babylonData, kind);
  62324. }
  62325. finally {
  62326. module.destroy(dracoData);
  62327. }
  62328. }
  62329. }
  62330. finally {
  62331. if (geometry) {
  62332. module.destroy(geometry);
  62333. }
  62334. module.destroy(decoder);
  62335. module.destroy(buffer);
  62336. }
  62337. return vertexData;
  62338. });
  62339. };
  62340. DracoCompression._GetDecoderModule = function () {
  62341. if (!DracoCompression._DecoderModulePromise) {
  62342. var promise = null;
  62343. var config_1 = {};
  62344. if (typeof DracoDecoderModule !== "undefined") {
  62345. promise = Promise.resolve();
  62346. }
  62347. else {
  62348. var decoder = DracoCompression.Configuration.decoder;
  62349. if (decoder) {
  62350. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62351. promise = Promise.all([
  62352. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62353. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62354. config_1.wasmBinary = data;
  62355. })
  62356. ]);
  62357. }
  62358. else if (decoder.fallbackUrl) {
  62359. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62360. }
  62361. }
  62362. }
  62363. if (!promise) {
  62364. throw new Error("Draco decoder module is not available");
  62365. }
  62366. DracoCompression._DecoderModulePromise = promise.then(function () {
  62367. return new Promise(function (resolve) {
  62368. config_1.onModuleLoaded = function (decoderModule) {
  62369. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62370. resolve({ module: decoderModule });
  62371. };
  62372. DracoDecoderModule(config_1);
  62373. });
  62374. });
  62375. }
  62376. return DracoCompression._DecoderModulePromise;
  62377. };
  62378. DracoCompression._LoadScriptAsync = function (url) {
  62379. return new Promise(function (resolve, reject) {
  62380. BABYLON.Tools.LoadScript(url, function () {
  62381. resolve();
  62382. }, function (message) {
  62383. reject(new Error(message));
  62384. });
  62385. });
  62386. };
  62387. DracoCompression._LoadFileAsync = function (url) {
  62388. return new Promise(function (resolve, reject) {
  62389. BABYLON.Tools.LoadFile(url, function (data) {
  62390. resolve(data);
  62391. }, undefined, undefined, true, function (request, exception) {
  62392. reject(exception);
  62393. });
  62394. });
  62395. };
  62396. /**
  62397. * The configuration. Defaults to the following urls:
  62398. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62399. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62400. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62401. */
  62402. DracoCompression.Configuration = {
  62403. decoder: {
  62404. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62405. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62406. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62407. }
  62408. };
  62409. return DracoCompression;
  62410. }());
  62411. BABYLON.DracoCompression = DracoCompression;
  62412. })(BABYLON || (BABYLON = {}));
  62413. //# sourceMappingURL=babylon.dracoCompression.js.map
  62414. var BABYLON;
  62415. (function (BABYLON) {
  62416. var AudioEngine = /** @class */ (function () {
  62417. function AudioEngine() {
  62418. this._audioContext = null;
  62419. this._audioContextInitialized = false;
  62420. this.canUseWebAudio = false;
  62421. this.WarnedWebAudioUnsupported = false;
  62422. this.unlocked = false;
  62423. this.isMP3supported = false;
  62424. this.isOGGsupported = false;
  62425. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62426. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62427. this.canUseWebAudio = true;
  62428. }
  62429. var audioElem = document.createElement('audio');
  62430. try {
  62431. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62432. this.isMP3supported = true;
  62433. }
  62434. }
  62435. catch (e) {
  62436. // protect error during capability check.
  62437. }
  62438. try {
  62439. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62440. this.isOGGsupported = true;
  62441. }
  62442. }
  62443. catch (e) {
  62444. // protect error during capability check.
  62445. }
  62446. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62447. this._unlockiOSaudio();
  62448. }
  62449. else {
  62450. this.unlocked = true;
  62451. }
  62452. }
  62453. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62454. get: function () {
  62455. if (!this._audioContextInitialized) {
  62456. this._initializeAudioContext();
  62457. }
  62458. return this._audioContext;
  62459. },
  62460. enumerable: true,
  62461. configurable: true
  62462. });
  62463. AudioEngine.prototype._unlockiOSaudio = function () {
  62464. var _this = this;
  62465. var unlockaudio = function () {
  62466. if (!_this.audioContext) {
  62467. return;
  62468. }
  62469. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62470. var source = _this.audioContext.createBufferSource();
  62471. source.buffer = buffer;
  62472. source.connect(_this.audioContext.destination);
  62473. source.start(0);
  62474. setTimeout(function () {
  62475. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62476. _this.unlocked = true;
  62477. window.removeEventListener('touchend', unlockaudio, false);
  62478. if (_this.onAudioUnlocked) {
  62479. _this.onAudioUnlocked();
  62480. }
  62481. }
  62482. }, 0);
  62483. };
  62484. window.addEventListener('touchend', unlockaudio, false);
  62485. };
  62486. AudioEngine.prototype._initializeAudioContext = function () {
  62487. try {
  62488. if (this.canUseWebAudio) {
  62489. this._audioContext = new AudioContext();
  62490. // create a global volume gain node
  62491. this.masterGain = this._audioContext.createGain();
  62492. this.masterGain.gain.value = 1;
  62493. this.masterGain.connect(this._audioContext.destination);
  62494. this._audioContextInitialized = true;
  62495. }
  62496. }
  62497. catch (e) {
  62498. this.canUseWebAudio = false;
  62499. BABYLON.Tools.Error("Web Audio: " + e.message);
  62500. }
  62501. };
  62502. AudioEngine.prototype.dispose = function () {
  62503. if (this.canUseWebAudio && this._audioContextInitialized) {
  62504. if (this._connectedAnalyser && this._audioContext) {
  62505. this._connectedAnalyser.stopDebugCanvas();
  62506. this._connectedAnalyser.dispose();
  62507. this.masterGain.disconnect();
  62508. this.masterGain.connect(this._audioContext.destination);
  62509. this._connectedAnalyser = null;
  62510. }
  62511. this.masterGain.gain.value = 1;
  62512. }
  62513. this.WarnedWebAudioUnsupported = false;
  62514. };
  62515. AudioEngine.prototype.getGlobalVolume = function () {
  62516. if (this.canUseWebAudio && this._audioContextInitialized) {
  62517. return this.masterGain.gain.value;
  62518. }
  62519. else {
  62520. return -1;
  62521. }
  62522. };
  62523. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62524. if (this.canUseWebAudio && this._audioContextInitialized) {
  62525. this.masterGain.gain.value = newVolume;
  62526. }
  62527. };
  62528. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62529. if (this._connectedAnalyser) {
  62530. this._connectedAnalyser.stopDebugCanvas();
  62531. }
  62532. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62533. this._connectedAnalyser = analyser;
  62534. this.masterGain.disconnect();
  62535. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62536. }
  62537. };
  62538. return AudioEngine;
  62539. }());
  62540. BABYLON.AudioEngine = AudioEngine;
  62541. })(BABYLON || (BABYLON = {}));
  62542. //# sourceMappingURL=babylon.audioEngine.js.map
  62543. var BABYLON;
  62544. (function (BABYLON) {
  62545. var Sound = /** @class */ (function () {
  62546. /**
  62547. * Create a sound and attach it to a scene
  62548. * @param name Name of your sound
  62549. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62550. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62551. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62552. */
  62553. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62554. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62555. var _this = this;
  62556. this.autoplay = false;
  62557. this.loop = false;
  62558. this.useCustomAttenuation = false;
  62559. this.spatialSound = false;
  62560. this.refDistance = 1;
  62561. this.rolloffFactor = 1;
  62562. this.maxDistance = 100;
  62563. this.distanceModel = "linear";
  62564. this._panningModel = "equalpower";
  62565. this._playbackRate = 1;
  62566. this._streaming = false;
  62567. this._startTime = 0;
  62568. this._startOffset = 0;
  62569. this._position = BABYLON.Vector3.Zero();
  62570. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62571. this._volume = 1;
  62572. this._isReadyToPlay = false;
  62573. this.isPlaying = false;
  62574. this.isPaused = false;
  62575. this._isDirectional = false;
  62576. // Used if you'd like to create a directional sound.
  62577. // If not set, the sound will be omnidirectional
  62578. this._coneInnerAngle = 360;
  62579. this._coneOuterAngle = 360;
  62580. this._coneOuterGain = 0;
  62581. this._isOutputConnected = false;
  62582. this._urlType = "Unknown";
  62583. this.name = name;
  62584. this._scene = scene;
  62585. this._readyToPlayCallback = readyToPlayCallback;
  62586. // Default custom attenuation function is a linear attenuation
  62587. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62588. if (currentDistance < maxDistance) {
  62589. return currentVolume * (1 - currentDistance / maxDistance);
  62590. }
  62591. else {
  62592. return 0;
  62593. }
  62594. };
  62595. if (options) {
  62596. this.autoplay = options.autoplay || false;
  62597. this.loop = options.loop || false;
  62598. // if volume === 0, we need another way to check this option
  62599. if (options.volume !== undefined) {
  62600. this._volume = options.volume;
  62601. }
  62602. this.spatialSound = options.spatialSound || false;
  62603. this.maxDistance = options.maxDistance || 100;
  62604. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62605. this.rolloffFactor = options.rolloffFactor || 1;
  62606. this.refDistance = options.refDistance || 1;
  62607. this.distanceModel = options.distanceModel || "linear";
  62608. this._playbackRate = options.playbackRate || 1;
  62609. this._streaming = options.streaming || false;
  62610. }
  62611. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62612. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62613. this._soundGain.gain.value = this._volume;
  62614. this._inputAudioNode = this._soundGain;
  62615. this._ouputAudioNode = this._soundGain;
  62616. if (this.spatialSound) {
  62617. this._createSpatialParameters();
  62618. }
  62619. this._scene.mainSoundTrack.AddSound(this);
  62620. var validParameter = true;
  62621. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62622. if (urlOrArrayBuffer) {
  62623. try {
  62624. if (typeof (urlOrArrayBuffer) === "string") {
  62625. this._urlType = "String";
  62626. }
  62627. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62628. this._urlType = "ArrayBuffer";
  62629. }
  62630. else if (urlOrArrayBuffer instanceof MediaStream) {
  62631. this._urlType = "MediaStream";
  62632. }
  62633. else if (Array.isArray(urlOrArrayBuffer)) {
  62634. this._urlType = "Array";
  62635. }
  62636. var urls = [];
  62637. var codecSupportedFound = false;
  62638. switch (this._urlType) {
  62639. case "MediaStream":
  62640. this._streaming = true;
  62641. this._isReadyToPlay = true;
  62642. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62643. if (this.autoplay) {
  62644. this.play();
  62645. }
  62646. if (this._readyToPlayCallback) {
  62647. this._readyToPlayCallback();
  62648. }
  62649. break;
  62650. case "ArrayBuffer":
  62651. if (urlOrArrayBuffer.byteLength > 0) {
  62652. codecSupportedFound = true;
  62653. this._soundLoaded(urlOrArrayBuffer);
  62654. }
  62655. break;
  62656. case "String":
  62657. urls.push(urlOrArrayBuffer);
  62658. case "Array":
  62659. if (urls.length === 0)
  62660. urls = urlOrArrayBuffer;
  62661. // If we found a supported format, we load it immediately and stop the loop
  62662. for (var i = 0; i < urls.length; i++) {
  62663. var url = urls[i];
  62664. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62665. codecSupportedFound = true;
  62666. }
  62667. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62668. codecSupportedFound = true;
  62669. }
  62670. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62671. codecSupportedFound = true;
  62672. }
  62673. if (url.indexOf("blob:") !== -1) {
  62674. codecSupportedFound = true;
  62675. }
  62676. if (codecSupportedFound) {
  62677. // Loading sound using XHR2
  62678. if (!this._streaming) {
  62679. this._scene._loadFile(url, function (data) {
  62680. _this._soundLoaded(data);
  62681. }, undefined, true, true, function (exception) {
  62682. if (exception) {
  62683. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62684. }
  62685. BABYLON.Tools.Error("Sound creation aborted.");
  62686. _this._scene.mainSoundTrack.RemoveSound(_this);
  62687. });
  62688. }
  62689. // Streaming sound using HTML5 Audio tag
  62690. else {
  62691. this._htmlAudioElement = new Audio(url);
  62692. this._htmlAudioElement.controls = false;
  62693. this._htmlAudioElement.loop = this.loop;
  62694. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62695. this._htmlAudioElement.preload = "auto";
  62696. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62697. _this._isReadyToPlay = true;
  62698. if (_this.autoplay) {
  62699. _this.play();
  62700. }
  62701. if (_this._readyToPlayCallback) {
  62702. _this._readyToPlayCallback();
  62703. }
  62704. });
  62705. document.body.appendChild(this._htmlAudioElement);
  62706. }
  62707. break;
  62708. }
  62709. }
  62710. break;
  62711. default:
  62712. validParameter = false;
  62713. break;
  62714. }
  62715. if (!validParameter) {
  62716. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62717. }
  62718. else {
  62719. if (!codecSupportedFound) {
  62720. this._isReadyToPlay = true;
  62721. // Simulating a ready to play event to avoid breaking code path
  62722. if (this._readyToPlayCallback) {
  62723. window.setTimeout(function () {
  62724. if (_this._readyToPlayCallback) {
  62725. _this._readyToPlayCallback();
  62726. }
  62727. }, 1000);
  62728. }
  62729. }
  62730. }
  62731. }
  62732. catch (ex) {
  62733. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62734. this._scene.mainSoundTrack.RemoveSound(this);
  62735. }
  62736. }
  62737. }
  62738. else {
  62739. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62740. this._scene.mainSoundTrack.AddSound(this);
  62741. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62742. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62743. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62744. }
  62745. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62746. if (this._readyToPlayCallback) {
  62747. window.setTimeout(function () {
  62748. if (_this._readyToPlayCallback) {
  62749. _this._readyToPlayCallback();
  62750. }
  62751. }, 1000);
  62752. }
  62753. }
  62754. }
  62755. Sound.prototype.dispose = function () {
  62756. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62757. if (this.isPlaying) {
  62758. this.stop();
  62759. }
  62760. this._isReadyToPlay = false;
  62761. if (this.soundTrackId === -1) {
  62762. this._scene.mainSoundTrack.RemoveSound(this);
  62763. }
  62764. else {
  62765. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62766. }
  62767. if (this._soundGain) {
  62768. this._soundGain.disconnect();
  62769. this._soundGain = null;
  62770. }
  62771. if (this._soundPanner) {
  62772. this._soundPanner.disconnect();
  62773. this._soundPanner = null;
  62774. }
  62775. if (this._soundSource) {
  62776. this._soundSource.disconnect();
  62777. this._soundSource = null;
  62778. }
  62779. this._audioBuffer = null;
  62780. if (this._htmlAudioElement) {
  62781. this._htmlAudioElement.pause();
  62782. this._htmlAudioElement.src = "";
  62783. document.body.removeChild(this._htmlAudioElement);
  62784. }
  62785. if (this._streamingSource) {
  62786. this._streamingSource.disconnect();
  62787. }
  62788. if (this._connectedMesh && this._registerFunc) {
  62789. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62790. this._connectedMesh = null;
  62791. }
  62792. }
  62793. };
  62794. Sound.prototype.isReady = function () {
  62795. return this._isReadyToPlay;
  62796. };
  62797. Sound.prototype._soundLoaded = function (audioData) {
  62798. var _this = this;
  62799. if (!BABYLON.Engine.audioEngine.audioContext) {
  62800. return;
  62801. }
  62802. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62803. _this._audioBuffer = buffer;
  62804. _this._isReadyToPlay = true;
  62805. if (_this.autoplay) {
  62806. _this.play();
  62807. }
  62808. if (_this._readyToPlayCallback) {
  62809. _this._readyToPlayCallback();
  62810. }
  62811. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62812. };
  62813. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62814. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62815. this._audioBuffer = audioBuffer;
  62816. this._isReadyToPlay = true;
  62817. }
  62818. };
  62819. Sound.prototype.updateOptions = function (options) {
  62820. if (options) {
  62821. this.loop = options.loop || this.loop;
  62822. this.maxDistance = options.maxDistance || this.maxDistance;
  62823. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62824. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62825. this.refDistance = options.refDistance || this.refDistance;
  62826. this.distanceModel = options.distanceModel || this.distanceModel;
  62827. this._playbackRate = options.playbackRate || this._playbackRate;
  62828. this._updateSpatialParameters();
  62829. if (this.isPlaying) {
  62830. if (this._streaming && this._htmlAudioElement) {
  62831. this._htmlAudioElement.playbackRate = this._playbackRate;
  62832. }
  62833. else {
  62834. if (this._soundSource) {
  62835. this._soundSource.playbackRate.value = this._playbackRate;
  62836. }
  62837. }
  62838. }
  62839. }
  62840. };
  62841. Sound.prototype._createSpatialParameters = function () {
  62842. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62843. if (this._scene.headphone) {
  62844. this._panningModel = "HRTF";
  62845. }
  62846. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62847. this._updateSpatialParameters();
  62848. this._soundPanner.connect(this._ouputAudioNode);
  62849. this._inputAudioNode = this._soundPanner;
  62850. }
  62851. };
  62852. Sound.prototype._updateSpatialParameters = function () {
  62853. if (this.spatialSound && this._soundPanner) {
  62854. if (this.useCustomAttenuation) {
  62855. // Tricks to disable in a way embedded Web Audio attenuation
  62856. this._soundPanner.distanceModel = "linear";
  62857. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62858. this._soundPanner.refDistance = 1;
  62859. this._soundPanner.rolloffFactor = 1;
  62860. this._soundPanner.panningModel = this._panningModel;
  62861. }
  62862. else {
  62863. this._soundPanner.distanceModel = this.distanceModel;
  62864. this._soundPanner.maxDistance = this.maxDistance;
  62865. this._soundPanner.refDistance = this.refDistance;
  62866. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62867. this._soundPanner.panningModel = this._panningModel;
  62868. }
  62869. }
  62870. };
  62871. Sound.prototype.switchPanningModelToHRTF = function () {
  62872. this._panningModel = "HRTF";
  62873. this._switchPanningModel();
  62874. };
  62875. Sound.prototype.switchPanningModelToEqualPower = function () {
  62876. this._panningModel = "equalpower";
  62877. this._switchPanningModel();
  62878. };
  62879. Sound.prototype._switchPanningModel = function () {
  62880. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62881. this._soundPanner.panningModel = this._panningModel;
  62882. }
  62883. };
  62884. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62885. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62886. if (this._isOutputConnected) {
  62887. this._ouputAudioNode.disconnect();
  62888. }
  62889. this._ouputAudioNode.connect(soundTrackAudioNode);
  62890. this._isOutputConnected = true;
  62891. }
  62892. };
  62893. /**
  62894. * Transform this sound into a directional source
  62895. * @param coneInnerAngle Size of the inner cone in degree
  62896. * @param coneOuterAngle Size of the outer cone in degree
  62897. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62898. */
  62899. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62900. if (coneOuterAngle < coneInnerAngle) {
  62901. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62902. return;
  62903. }
  62904. this._coneInnerAngle = coneInnerAngle;
  62905. this._coneOuterAngle = coneOuterAngle;
  62906. this._coneOuterGain = coneOuterGain;
  62907. this._isDirectional = true;
  62908. if (this.isPlaying && this.loop) {
  62909. this.stop();
  62910. this.play();
  62911. }
  62912. };
  62913. Sound.prototype.setPosition = function (newPosition) {
  62914. this._position = newPosition;
  62915. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62916. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62917. }
  62918. };
  62919. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62920. this._localDirection = newLocalDirection;
  62921. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62922. this._updateDirection();
  62923. }
  62924. };
  62925. Sound.prototype._updateDirection = function () {
  62926. if (!this._connectedMesh || !this._soundPanner) {
  62927. return;
  62928. }
  62929. var mat = this._connectedMesh.getWorldMatrix();
  62930. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62931. direction.normalize();
  62932. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62933. };
  62934. Sound.prototype.updateDistanceFromListener = function () {
  62935. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62936. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62937. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62938. }
  62939. };
  62940. Sound.prototype.setAttenuationFunction = function (callback) {
  62941. this._customAttenuationFunction = callback;
  62942. };
  62943. /**
  62944. * Play the sound
  62945. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62946. * @param offset (optional) Start the sound setting it at a specific time
  62947. */
  62948. Sound.prototype.play = function (time, offset) {
  62949. var _this = this;
  62950. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62951. try {
  62952. if (this._startOffset < 0) {
  62953. time = -this._startOffset;
  62954. this._startOffset = 0;
  62955. }
  62956. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62957. if (!this._soundSource || !this._streamingSource) {
  62958. if (this.spatialSound && this._soundPanner) {
  62959. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62960. if (this._isDirectional) {
  62961. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62962. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62963. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62964. if (this._connectedMesh) {
  62965. this._updateDirection();
  62966. }
  62967. else {
  62968. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62969. }
  62970. }
  62971. }
  62972. }
  62973. if (this._streaming) {
  62974. if (!this._streamingSource) {
  62975. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62976. this._htmlAudioElement.onended = function () { _this._onended(); };
  62977. this._htmlAudioElement.playbackRate = this._playbackRate;
  62978. }
  62979. this._streamingSource.disconnect();
  62980. this._streamingSource.connect(this._inputAudioNode);
  62981. if (this._htmlAudioElement) {
  62982. this._htmlAudioElement.play();
  62983. }
  62984. }
  62985. else {
  62986. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62987. this._soundSource.buffer = this._audioBuffer;
  62988. this._soundSource.connect(this._inputAudioNode);
  62989. this._soundSource.loop = this.loop;
  62990. this._soundSource.playbackRate.value = this._playbackRate;
  62991. this._soundSource.onended = function () { _this._onended(); };
  62992. if (this._soundSource.buffer) {
  62993. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62994. }
  62995. }
  62996. this._startTime = startTime;
  62997. this.isPlaying = true;
  62998. this.isPaused = false;
  62999. }
  63000. catch (ex) {
  63001. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63002. }
  63003. }
  63004. };
  63005. Sound.prototype._onended = function () {
  63006. this.isPlaying = false;
  63007. if (this.onended) {
  63008. this.onended();
  63009. }
  63010. };
  63011. /**
  63012. * Stop the sound
  63013. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63014. */
  63015. Sound.prototype.stop = function (time) {
  63016. if (this.isPlaying) {
  63017. if (this._streaming) {
  63018. if (this._htmlAudioElement) {
  63019. this._htmlAudioElement.pause();
  63020. // Test needed for Firefox or it will generate an Invalid State Error
  63021. if (this._htmlAudioElement.currentTime > 0) {
  63022. this._htmlAudioElement.currentTime = 0;
  63023. }
  63024. }
  63025. else {
  63026. this._streamingSource.disconnect();
  63027. }
  63028. }
  63029. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63030. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63031. this._soundSource.stop(stopTime);
  63032. this._soundSource.onended = function () { };
  63033. if (!this.isPaused) {
  63034. this._startOffset = 0;
  63035. }
  63036. }
  63037. this.isPlaying = false;
  63038. }
  63039. };
  63040. Sound.prototype.pause = function () {
  63041. if (this.isPlaying) {
  63042. this.isPaused = true;
  63043. if (this._streaming) {
  63044. if (this._htmlAudioElement) {
  63045. this._htmlAudioElement.pause();
  63046. }
  63047. else {
  63048. this._streamingSource.disconnect();
  63049. }
  63050. }
  63051. else if (BABYLON.Engine.audioEngine.audioContext) {
  63052. this.stop(0);
  63053. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63054. }
  63055. }
  63056. };
  63057. Sound.prototype.setVolume = function (newVolume, time) {
  63058. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63059. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63060. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63061. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63062. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63063. }
  63064. else {
  63065. this._soundGain.gain.value = newVolume;
  63066. }
  63067. }
  63068. this._volume = newVolume;
  63069. };
  63070. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63071. this._playbackRate = newPlaybackRate;
  63072. if (this.isPlaying) {
  63073. if (this._streaming && this._htmlAudioElement) {
  63074. this._htmlAudioElement.playbackRate = this._playbackRate;
  63075. }
  63076. else if (this._soundSource) {
  63077. this._soundSource.playbackRate.value = this._playbackRate;
  63078. }
  63079. }
  63080. };
  63081. Sound.prototype.getVolume = function () {
  63082. return this._volume;
  63083. };
  63084. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63085. var _this = this;
  63086. if (this._connectedMesh && this._registerFunc) {
  63087. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63088. this._registerFunc = null;
  63089. }
  63090. this._connectedMesh = meshToConnectTo;
  63091. if (!this.spatialSound) {
  63092. this.spatialSound = true;
  63093. this._createSpatialParameters();
  63094. if (this.isPlaying && this.loop) {
  63095. this.stop();
  63096. this.play();
  63097. }
  63098. }
  63099. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63100. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63101. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63102. };
  63103. Sound.prototype.detachFromMesh = function () {
  63104. if (this._connectedMesh && this._registerFunc) {
  63105. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63106. this._registerFunc = null;
  63107. this._connectedMesh = null;
  63108. }
  63109. };
  63110. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63111. if (!node.getBoundingInfo) {
  63112. return;
  63113. }
  63114. var mesh = node;
  63115. var boundingInfo = mesh.getBoundingInfo();
  63116. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63117. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63118. this._updateDirection();
  63119. }
  63120. };
  63121. Sound.prototype.clone = function () {
  63122. var _this = this;
  63123. if (!this._streaming) {
  63124. var setBufferAndRun = function () {
  63125. if (_this._isReadyToPlay) {
  63126. clonedSound._audioBuffer = _this.getAudioBuffer();
  63127. clonedSound._isReadyToPlay = true;
  63128. if (clonedSound.autoplay) {
  63129. clonedSound.play();
  63130. }
  63131. }
  63132. else {
  63133. window.setTimeout(setBufferAndRun, 300);
  63134. }
  63135. };
  63136. var currentOptions = {
  63137. autoplay: this.autoplay, loop: this.loop,
  63138. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63139. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63140. refDistance: this.refDistance, distanceModel: this.distanceModel
  63141. };
  63142. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63143. if (this.useCustomAttenuation) {
  63144. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63145. }
  63146. clonedSound.setPosition(this._position);
  63147. clonedSound.setPlaybackRate(this._playbackRate);
  63148. setBufferAndRun();
  63149. return clonedSound;
  63150. }
  63151. // Can't clone a streaming sound
  63152. else {
  63153. return null;
  63154. }
  63155. };
  63156. Sound.prototype.getAudioBuffer = function () {
  63157. return this._audioBuffer;
  63158. };
  63159. Sound.prototype.serialize = function () {
  63160. var serializationObject = {
  63161. name: this.name,
  63162. url: this.name,
  63163. autoplay: this.autoplay,
  63164. loop: this.loop,
  63165. volume: this._volume,
  63166. spatialSound: this.spatialSound,
  63167. maxDistance: this.maxDistance,
  63168. rolloffFactor: this.rolloffFactor,
  63169. refDistance: this.refDistance,
  63170. distanceModel: this.distanceModel,
  63171. playbackRate: this._playbackRate,
  63172. panningModel: this._panningModel,
  63173. soundTrackId: this.soundTrackId
  63174. };
  63175. if (this.spatialSound) {
  63176. if (this._connectedMesh)
  63177. serializationObject.connectedMeshId = this._connectedMesh.id;
  63178. serializationObject.position = this._position.asArray();
  63179. serializationObject.refDistance = this.refDistance;
  63180. serializationObject.distanceModel = this.distanceModel;
  63181. serializationObject.isDirectional = this._isDirectional;
  63182. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63183. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63184. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63185. serializationObject.coneOuterGain = this._coneOuterGain;
  63186. }
  63187. return serializationObject;
  63188. };
  63189. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63190. var soundName = parsedSound.name;
  63191. var soundUrl;
  63192. if (parsedSound.url) {
  63193. soundUrl = rootUrl + parsedSound.url;
  63194. }
  63195. else {
  63196. soundUrl = rootUrl + soundName;
  63197. }
  63198. var options = {
  63199. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63200. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63201. rolloffFactor: parsedSound.rolloffFactor,
  63202. refDistance: parsedSound.refDistance,
  63203. distanceModel: parsedSound.distanceModel,
  63204. playbackRate: parsedSound.playbackRate
  63205. };
  63206. var newSound;
  63207. if (!sourceSound) {
  63208. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63209. scene._addPendingData(newSound);
  63210. }
  63211. else {
  63212. var setBufferAndRun = function () {
  63213. if (sourceSound._isReadyToPlay) {
  63214. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63215. newSound._isReadyToPlay = true;
  63216. if (newSound.autoplay) {
  63217. newSound.play();
  63218. }
  63219. }
  63220. else {
  63221. window.setTimeout(setBufferAndRun, 300);
  63222. }
  63223. };
  63224. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63225. setBufferAndRun();
  63226. }
  63227. if (parsedSound.position) {
  63228. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63229. newSound.setPosition(soundPosition);
  63230. }
  63231. if (parsedSound.isDirectional) {
  63232. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63233. if (parsedSound.localDirectionToMesh) {
  63234. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63235. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63236. }
  63237. }
  63238. if (parsedSound.connectedMeshId) {
  63239. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63240. if (connectedMesh) {
  63241. newSound.attachToMesh(connectedMesh);
  63242. }
  63243. }
  63244. return newSound;
  63245. };
  63246. return Sound;
  63247. }());
  63248. BABYLON.Sound = Sound;
  63249. })(BABYLON || (BABYLON = {}));
  63250. //# sourceMappingURL=babylon.sound.js.map
  63251. var BABYLON;
  63252. (function (BABYLON) {
  63253. var SoundTrack = /** @class */ (function () {
  63254. function SoundTrack(scene, options) {
  63255. this.id = -1;
  63256. this._isMainTrack = false;
  63257. this._isInitialized = false;
  63258. this._scene = scene;
  63259. this.soundCollection = new Array();
  63260. this._options = options;
  63261. if (!this._isMainTrack) {
  63262. this._scene.soundTracks.push(this);
  63263. this.id = this._scene.soundTracks.length - 1;
  63264. }
  63265. }
  63266. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63267. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63268. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63269. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63270. if (this._options) {
  63271. if (this._options.volume) {
  63272. this._outputAudioNode.gain.value = this._options.volume;
  63273. }
  63274. if (this._options.mainTrack) {
  63275. this._isMainTrack = this._options.mainTrack;
  63276. }
  63277. }
  63278. this._isInitialized = true;
  63279. }
  63280. };
  63281. SoundTrack.prototype.dispose = function () {
  63282. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63283. if (this._connectedAnalyser) {
  63284. this._connectedAnalyser.stopDebugCanvas();
  63285. }
  63286. while (this.soundCollection.length) {
  63287. this.soundCollection[0].dispose();
  63288. }
  63289. if (this._outputAudioNode) {
  63290. this._outputAudioNode.disconnect();
  63291. }
  63292. this._outputAudioNode = null;
  63293. }
  63294. };
  63295. SoundTrack.prototype.AddSound = function (sound) {
  63296. if (!this._isInitialized) {
  63297. this._initializeSoundTrackAudioGraph();
  63298. }
  63299. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63300. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63301. }
  63302. if (sound.soundTrackId) {
  63303. if (sound.soundTrackId === -1) {
  63304. this._scene.mainSoundTrack.RemoveSound(sound);
  63305. }
  63306. else {
  63307. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63308. }
  63309. }
  63310. this.soundCollection.push(sound);
  63311. sound.soundTrackId = this.id;
  63312. };
  63313. SoundTrack.prototype.RemoveSound = function (sound) {
  63314. var index = this.soundCollection.indexOf(sound);
  63315. if (index !== -1) {
  63316. this.soundCollection.splice(index, 1);
  63317. }
  63318. };
  63319. SoundTrack.prototype.setVolume = function (newVolume) {
  63320. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63321. this._outputAudioNode.gain.value = newVolume;
  63322. }
  63323. };
  63324. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63325. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63326. for (var i = 0; i < this.soundCollection.length; i++) {
  63327. this.soundCollection[i].switchPanningModelToHRTF();
  63328. }
  63329. }
  63330. };
  63331. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63332. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63333. for (var i = 0; i < this.soundCollection.length; i++) {
  63334. this.soundCollection[i].switchPanningModelToEqualPower();
  63335. }
  63336. }
  63337. };
  63338. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63339. if (this._connectedAnalyser) {
  63340. this._connectedAnalyser.stopDebugCanvas();
  63341. }
  63342. this._connectedAnalyser = analyser;
  63343. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63344. this._outputAudioNode.disconnect();
  63345. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63346. }
  63347. };
  63348. return SoundTrack;
  63349. }());
  63350. BABYLON.SoundTrack = SoundTrack;
  63351. })(BABYLON || (BABYLON = {}));
  63352. //# sourceMappingURL=babylon.soundtrack.js.map
  63353. var BABYLON;
  63354. (function (BABYLON) {
  63355. /**
  63356. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63357. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63358. */
  63359. var Analyser = /** @class */ (function () {
  63360. /**
  63361. * Creates a new analyser
  63362. * @param scene defines hosting scene
  63363. */
  63364. function Analyser(scene) {
  63365. /**
  63366. * Gets or sets the smoothing
  63367. * @ignorenaming
  63368. */
  63369. this.SMOOTHING = 0.75;
  63370. /**
  63371. * Gets or sets the FFT table size
  63372. * @ignorenaming
  63373. */
  63374. this.FFT_SIZE = 512;
  63375. /**
  63376. * Gets or sets the bar graph amplitude
  63377. * @ignorenaming
  63378. */
  63379. this.BARGRAPHAMPLITUDE = 256;
  63380. /**
  63381. * Gets or sets the position of the debug canvas
  63382. * @ignorenaming
  63383. */
  63384. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63385. /**
  63386. * Gets or sets the debug canvas size
  63387. * @ignorenaming
  63388. */
  63389. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63390. this._scene = scene;
  63391. this._audioEngine = BABYLON.Engine.audioEngine;
  63392. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63393. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63394. this._webAudioAnalyser.minDecibels = -140;
  63395. this._webAudioAnalyser.maxDecibels = 0;
  63396. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63397. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63398. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63399. }
  63400. }
  63401. /**
  63402. * Get the number of data values you will have to play with for the visualization
  63403. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63404. * @returns a number
  63405. */
  63406. Analyser.prototype.getFrequencyBinCount = function () {
  63407. if (this._audioEngine.canUseWebAudio) {
  63408. return this._webAudioAnalyser.frequencyBinCount;
  63409. }
  63410. else {
  63411. return 0;
  63412. }
  63413. };
  63414. /**
  63415. * Gets the current frequency data as a byte array
  63416. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63417. * @returns a Uint8Array
  63418. */
  63419. Analyser.prototype.getByteFrequencyData = function () {
  63420. if (this._audioEngine.canUseWebAudio) {
  63421. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63422. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63423. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63424. }
  63425. return this._byteFreqs;
  63426. };
  63427. /**
  63428. * Gets the current waveform as a byte array
  63429. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63430. * @returns a Uint8Array
  63431. */
  63432. Analyser.prototype.getByteTimeDomainData = function () {
  63433. if (this._audioEngine.canUseWebAudio) {
  63434. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63435. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63436. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63437. }
  63438. return this._byteTime;
  63439. };
  63440. /**
  63441. * Gets the current frequency data as a float array
  63442. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63443. * @returns a Float32Array
  63444. */
  63445. Analyser.prototype.getFloatFrequencyData = function () {
  63446. if (this._audioEngine.canUseWebAudio) {
  63447. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63448. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63449. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63450. }
  63451. return this._floatFreqs;
  63452. };
  63453. /**
  63454. * Renders the debug canvas
  63455. */
  63456. Analyser.prototype.drawDebugCanvas = function () {
  63457. var _this = this;
  63458. if (this._audioEngine.canUseWebAudio) {
  63459. if (!this._debugCanvas) {
  63460. this._debugCanvas = document.createElement("canvas");
  63461. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63462. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63463. this._debugCanvas.style.position = "absolute";
  63464. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63465. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63466. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63467. document.body.appendChild(this._debugCanvas);
  63468. this._registerFunc = function () {
  63469. _this.drawDebugCanvas();
  63470. };
  63471. this._scene.registerBeforeRender(this._registerFunc);
  63472. }
  63473. if (this._registerFunc && this._debugCanvasContext) {
  63474. var workingArray = this.getByteFrequencyData();
  63475. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63476. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63477. // Draw the frequency domain chart.
  63478. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63479. var value = workingArray[i];
  63480. var percent = value / this.BARGRAPHAMPLITUDE;
  63481. var height = this.DEBUGCANVASSIZE.height * percent;
  63482. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63483. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63484. var hue = i / this.getFrequencyBinCount() * 360;
  63485. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63486. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63487. }
  63488. }
  63489. }
  63490. };
  63491. /**
  63492. * Stops rendering the debug canvas and removes it
  63493. */
  63494. Analyser.prototype.stopDebugCanvas = function () {
  63495. if (this._debugCanvas) {
  63496. if (this._registerFunc) {
  63497. this._scene.unregisterBeforeRender(this._registerFunc);
  63498. this._registerFunc = null;
  63499. }
  63500. document.body.removeChild(this._debugCanvas);
  63501. this._debugCanvas = null;
  63502. this._debugCanvasContext = null;
  63503. }
  63504. };
  63505. /**
  63506. * Connects two audio nodes
  63507. * @param inputAudioNode defines first node to connect
  63508. * @param outputAudioNode defines second node to connect
  63509. */
  63510. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63511. if (this._audioEngine.canUseWebAudio) {
  63512. inputAudioNode.connect(this._webAudioAnalyser);
  63513. this._webAudioAnalyser.connect(outputAudioNode);
  63514. }
  63515. };
  63516. /**
  63517. * Releases all associated resources
  63518. */
  63519. Analyser.prototype.dispose = function () {
  63520. if (this._audioEngine.canUseWebAudio) {
  63521. this._webAudioAnalyser.disconnect();
  63522. }
  63523. };
  63524. return Analyser;
  63525. }());
  63526. BABYLON.Analyser = Analyser;
  63527. })(BABYLON || (BABYLON = {}));
  63528. //# sourceMappingURL=babylon.analyser.js.map
  63529. var BABYLON;
  63530. (function (BABYLON) {
  63531. var CubeTexture = /** @class */ (function (_super) {
  63532. __extends(CubeTexture, _super);
  63533. /**
  63534. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63535. * as prefiltered data.
  63536. * @param rootUrl defines the url of the texture or the root name of the six images
  63537. * @param scene defines the scene the texture is attached to
  63538. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63539. * @param noMipmap defines if mipmaps should be created or not
  63540. * @param files defines the six files to load for the different faces
  63541. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63542. * @param onError defines a callback triggered in case of error during load
  63543. * @param format defines the internal format to use for the texture once loaded
  63544. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63545. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63546. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63547. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63548. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63549. * @return the cube texture
  63550. */
  63551. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63552. if (extensions === void 0) { extensions = null; }
  63553. if (noMipmap === void 0) { noMipmap = false; }
  63554. if (files === void 0) { files = null; }
  63555. if (onLoad === void 0) { onLoad = null; }
  63556. if (onError === void 0) { onError = null; }
  63557. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63558. if (prefiltered === void 0) { prefiltered = false; }
  63559. if (forcedExtension === void 0) { forcedExtension = null; }
  63560. if (createPolynomials === void 0) { createPolynomials = false; }
  63561. if (lodScale === void 0) { lodScale = 0.8; }
  63562. if (lodOffset === void 0) { lodOffset = 0; }
  63563. var _this = _super.call(this, scene) || this;
  63564. /**
  63565. * Gets or sets the center of the bounding box associated with the cube texture
  63566. * It must define where the camera used to render the texture was set
  63567. */
  63568. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63569. _this._rotationY = 0;
  63570. /** @hidden */
  63571. _this._prefiltered = false;
  63572. _this.name = rootUrl;
  63573. _this.url = rootUrl;
  63574. _this._noMipmap = noMipmap;
  63575. _this.hasAlpha = false;
  63576. _this._format = format;
  63577. _this.isCube = true;
  63578. _this._textureMatrix = BABYLON.Matrix.Identity();
  63579. _this._createPolynomials = createPolynomials;
  63580. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63581. if (!rootUrl && !files) {
  63582. return _this;
  63583. }
  63584. var lastDot = rootUrl.lastIndexOf(".");
  63585. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63586. var isDDS = (extension === ".dds");
  63587. var isEnv = (extension === ".env");
  63588. if (isEnv) {
  63589. _this.gammaSpace = false;
  63590. _this._prefiltered = false;
  63591. }
  63592. else {
  63593. _this._prefiltered = prefiltered;
  63594. if (prefiltered) {
  63595. _this.gammaSpace = false;
  63596. }
  63597. }
  63598. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63599. if (!files) {
  63600. if (!isEnv && !isDDS && !extensions) {
  63601. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63602. }
  63603. files = [];
  63604. if (extensions) {
  63605. for (var index = 0; index < extensions.length; index++) {
  63606. files.push(rootUrl + extensions[index]);
  63607. }
  63608. }
  63609. }
  63610. _this._files = files;
  63611. if (!_this._texture) {
  63612. if (!scene.useDelayedTextureLoading) {
  63613. if (prefiltered) {
  63614. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63615. }
  63616. else {
  63617. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63618. }
  63619. }
  63620. else {
  63621. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63622. }
  63623. }
  63624. else if (onLoad) {
  63625. if (_this._texture.isReady) {
  63626. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63627. }
  63628. else {
  63629. _this._texture.onLoadedObservable.add(onLoad);
  63630. }
  63631. }
  63632. return _this;
  63633. }
  63634. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63635. get: function () {
  63636. return this._boundingBoxSize;
  63637. },
  63638. /**
  63639. * Gets or sets the size of the bounding box associated with the cube texture
  63640. * When defined, the cubemap will switch to local mode
  63641. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63642. * @example https://www.babylonjs-playground.com/#RNASML
  63643. */
  63644. set: function (value) {
  63645. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63646. return;
  63647. }
  63648. this._boundingBoxSize = value;
  63649. var scene = this.getScene();
  63650. if (scene) {
  63651. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63652. }
  63653. },
  63654. enumerable: true,
  63655. configurable: true
  63656. });
  63657. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63658. /**
  63659. * Gets texture matrix rotation angle around Y axis radians.
  63660. */
  63661. get: function () {
  63662. return this._rotationY;
  63663. },
  63664. /**
  63665. * Sets texture matrix rotation angle around Y axis in radians.
  63666. */
  63667. set: function (value) {
  63668. this._rotationY = value;
  63669. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63670. },
  63671. enumerable: true,
  63672. configurable: true
  63673. });
  63674. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63675. var rootUrlKey = "";
  63676. files.forEach(function (url) { return rootUrlKey += url; });
  63677. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63678. };
  63679. /**
  63680. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63681. * @param url defines the url of the prefiltered texture
  63682. * @param scene defines the scene the texture is attached to
  63683. * @param forcedExtension defines the extension of the file if different from the url
  63684. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63685. * @return the prefiltered texture
  63686. */
  63687. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63688. if (forcedExtension === void 0) { forcedExtension = null; }
  63689. if (createPolynomials === void 0) { createPolynomials = true; }
  63690. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63691. };
  63692. // Methods
  63693. CubeTexture.prototype.delayLoad = function () {
  63694. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63695. return;
  63696. }
  63697. var scene = this.getScene();
  63698. if (!scene) {
  63699. return;
  63700. }
  63701. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63702. this._texture = this._getFromCache(this.url, this._noMipmap);
  63703. if (!this._texture) {
  63704. if (this._prefiltered) {
  63705. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63706. }
  63707. else {
  63708. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63709. }
  63710. }
  63711. };
  63712. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63713. return this._textureMatrix;
  63714. };
  63715. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63716. this._textureMatrix = value;
  63717. };
  63718. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63719. var texture = BABYLON.SerializationHelper.Parse(function () {
  63720. var prefiltered = false;
  63721. if (parsedTexture.prefiltered) {
  63722. prefiltered = parsedTexture.prefiltered;
  63723. }
  63724. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63725. }, parsedTexture, scene);
  63726. // Local Cubemaps
  63727. if (parsedTexture.boundingBoxPosition) {
  63728. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63729. }
  63730. if (parsedTexture.boundingBoxSize) {
  63731. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63732. }
  63733. // Animations
  63734. if (parsedTexture.animations) {
  63735. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63736. var parsedAnimation = parsedTexture.animations[animationIndex];
  63737. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63738. }
  63739. }
  63740. return texture;
  63741. };
  63742. CubeTexture.prototype.clone = function () {
  63743. var _this = this;
  63744. return BABYLON.SerializationHelper.Clone(function () {
  63745. var scene = _this.getScene();
  63746. if (!scene) {
  63747. return _this;
  63748. }
  63749. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63750. }, this);
  63751. };
  63752. __decorate([
  63753. BABYLON.serialize("rotationY")
  63754. ], CubeTexture.prototype, "_rotationY", void 0);
  63755. return CubeTexture;
  63756. }(BABYLON.BaseTexture));
  63757. BABYLON.CubeTexture = CubeTexture;
  63758. })(BABYLON || (BABYLON = {}));
  63759. //# sourceMappingURL=babylon.cubeTexture.js.map
  63760. var BABYLON;
  63761. (function (BABYLON) {
  63762. /**
  63763. * Raw cube texture where the raw buffers are passed in
  63764. */
  63765. var RawCubeTexture = /** @class */ (function (_super) {
  63766. __extends(RawCubeTexture, _super);
  63767. /**
  63768. * Creates a cube texture where the raw buffers are passed in.
  63769. * @param scene defines the scene the texture is attached to
  63770. * @param data defines the array of data to use to create each face
  63771. * @param size defines the size of the textures
  63772. * @param format defines the format of the data
  63773. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  63774. * @param generateMipMaps defines if the engine should generate the mip levels
  63775. * @param invertY defines if data must be stored with Y axis inverted
  63776. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  63777. * @param compression defines the compression used (null by default)
  63778. */
  63779. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  63780. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63781. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63782. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63783. if (invertY === void 0) { invertY = false; }
  63784. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63785. if (compression === void 0) { compression = null; }
  63786. var _this = _super.call(this, "", scene) || this;
  63787. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  63788. return _this;
  63789. }
  63790. /**
  63791. * Updates the raw cube texture.
  63792. * @param data defines the data to store
  63793. * @param format defines the data format
  63794. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  63795. * @param invertY defines if data must be stored with Y axis inverted
  63796. * @param compression defines the compression used (null by default)
  63797. * @param level defines which level of the texture to update
  63798. */
  63799. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  63800. if (compression === void 0) { compression = null; }
  63801. if (level === void 0) { level = 0; }
  63802. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  63803. };
  63804. /**
  63805. * Updates a raw cube texture with RGBD encoded data.
  63806. * @param data defines the array of data [mipmap][face] to use to create each face
  63807. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  63808. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63809. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63810. * @returns a promsie that resolves when the operation is complete
  63811. */
  63812. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  63813. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  63814. if (lodScale === void 0) { lodScale = 0.8; }
  63815. if (lodOffset === void 0) { lodOffset = 0; }
  63816. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  63817. };
  63818. /**
  63819. * Clones the raw cube texture.
  63820. * @return a new cube texture
  63821. */
  63822. RawCubeTexture.prototype.clone = function () {
  63823. var _this = this;
  63824. return BABYLON.SerializationHelper.Clone(function () {
  63825. var scene = _this.getScene();
  63826. var internalTexture = _this._texture;
  63827. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  63828. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  63829. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  63830. }
  63831. return texture;
  63832. }, this);
  63833. };
  63834. /** @hidden */
  63835. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  63836. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  63837. internalTexture._bufferViewArrayArray = data;
  63838. internalTexture._lodGenerationScale = lodScale;
  63839. internalTexture._lodGenerationOffset = lodOffset;
  63840. internalTexture._sphericalPolynomial = sphericalPolynomial;
  63841. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  63842. internalTexture.isReady = true;
  63843. });
  63844. };
  63845. return RawCubeTexture;
  63846. }(BABYLON.CubeTexture));
  63847. BABYLON.RawCubeTexture = RawCubeTexture;
  63848. })(BABYLON || (BABYLON = {}));
  63849. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  63850. var BABYLON;
  63851. (function (BABYLON) {
  63852. var RenderTargetTexture = /** @class */ (function (_super) {
  63853. __extends(RenderTargetTexture, _super);
  63854. /**
  63855. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63856. * or used a shadow, depth texture...
  63857. * @param name The friendly name of the texture
  63858. * @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)
  63859. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63860. * @param generateMipMaps True if mip maps need to be generated after render.
  63861. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63862. * @param type The type of the buffer in the RTT (int, half float, float...)
  63863. * @param isCube True if a cube texture needs to be created
  63864. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63865. * @param generateDepthBuffer True to generate a depth buffer
  63866. * @param generateStencilBuffer True to generate a stencil buffer
  63867. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63868. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63869. */
  63870. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63871. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63872. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63873. if (isCube === void 0) { isCube = false; }
  63874. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63875. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63876. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63877. if (isMulti === void 0) { isMulti = false; }
  63878. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63879. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63880. _this.isCube = isCube;
  63881. /**
  63882. * Use this list to define the list of mesh you want to render.
  63883. */
  63884. _this.renderList = new Array();
  63885. _this.renderParticles = true;
  63886. _this.renderSprites = false;
  63887. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63888. _this.ignoreCameraViewport = false;
  63889. // Events
  63890. /**
  63891. * An event triggered when the texture is unbind.
  63892. */
  63893. _this.onBeforeBindObservable = new BABYLON.Observable();
  63894. /**
  63895. * An event triggered when the texture is unbind.
  63896. */
  63897. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63898. /**
  63899. * An event triggered before rendering the texture
  63900. */
  63901. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63902. /**
  63903. * An event triggered after rendering the texture
  63904. */
  63905. _this.onAfterRenderObservable = new BABYLON.Observable();
  63906. /**
  63907. * An event triggered after the texture clear
  63908. */
  63909. _this.onClearObservable = new BABYLON.Observable();
  63910. _this._currentRefreshId = -1;
  63911. _this._refreshRate = 1;
  63912. _this._samples = 1;
  63913. /**
  63914. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63915. * It must define where the camera used to render the texture is set
  63916. */
  63917. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63918. scene = _this.getScene();
  63919. if (!scene) {
  63920. return _this;
  63921. }
  63922. _this._engine = scene.getEngine();
  63923. _this.name = name;
  63924. _this.isRenderTarget = true;
  63925. _this._initialSizeParameter = size;
  63926. _this._processSizeParameter(size);
  63927. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63928. });
  63929. _this._generateMipMaps = generateMipMaps ? true : false;
  63930. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63931. // Rendering groups
  63932. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63933. if (isMulti) {
  63934. return _this;
  63935. }
  63936. _this._renderTargetOptions = {
  63937. generateMipMaps: generateMipMaps,
  63938. type: type,
  63939. format: format,
  63940. samplingMode: samplingMode,
  63941. generateDepthBuffer: generateDepthBuffer,
  63942. generateStencilBuffer: generateStencilBuffer
  63943. };
  63944. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63945. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63946. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63947. }
  63948. if (isCube) {
  63949. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63950. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63951. _this._textureMatrix = BABYLON.Matrix.Identity();
  63952. }
  63953. else {
  63954. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63955. }
  63956. return _this;
  63957. }
  63958. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63959. get: function () {
  63960. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63961. },
  63962. enumerable: true,
  63963. configurable: true
  63964. });
  63965. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63966. get: function () {
  63967. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63968. },
  63969. enumerable: true,
  63970. configurable: true
  63971. });
  63972. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63973. get: function () {
  63974. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63975. },
  63976. enumerable: true,
  63977. configurable: true
  63978. });
  63979. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63980. set: function (callback) {
  63981. if (this._onAfterUnbindObserver) {
  63982. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63983. }
  63984. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63985. },
  63986. enumerable: true,
  63987. configurable: true
  63988. });
  63989. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63990. set: function (callback) {
  63991. if (this._onBeforeRenderObserver) {
  63992. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63993. }
  63994. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63995. },
  63996. enumerable: true,
  63997. configurable: true
  63998. });
  63999. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64000. set: function (callback) {
  64001. if (this._onAfterRenderObserver) {
  64002. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64003. }
  64004. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64005. },
  64006. enumerable: true,
  64007. configurable: true
  64008. });
  64009. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64010. set: function (callback) {
  64011. if (this._onClearObserver) {
  64012. this.onClearObservable.remove(this._onClearObserver);
  64013. }
  64014. this._onClearObserver = this.onClearObservable.add(callback);
  64015. },
  64016. enumerable: true,
  64017. configurable: true
  64018. });
  64019. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64020. get: function () {
  64021. return this._renderTargetOptions;
  64022. },
  64023. enumerable: true,
  64024. configurable: true
  64025. });
  64026. RenderTargetTexture.prototype._onRatioRescale = function () {
  64027. if (this._sizeRatio) {
  64028. this.resize(this._initialSizeParameter);
  64029. }
  64030. };
  64031. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64032. get: function () {
  64033. return this._boundingBoxSize;
  64034. },
  64035. /**
  64036. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64037. * When defined, the cubemap will switch to local mode
  64038. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64039. * @example https://www.babylonjs-playground.com/#RNASML
  64040. */
  64041. set: function (value) {
  64042. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64043. return;
  64044. }
  64045. this._boundingBoxSize = value;
  64046. var scene = this.getScene();
  64047. if (scene) {
  64048. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64049. }
  64050. },
  64051. enumerable: true,
  64052. configurable: true
  64053. });
  64054. /**
  64055. * Creates a depth stencil texture.
  64056. * This is only available in WebGL 2 or with the depth texture extension available.
  64057. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64058. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64059. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64060. */
  64061. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64062. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64063. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64064. if (generateStencil === void 0) { generateStencil = false; }
  64065. if (!this.getScene()) {
  64066. return;
  64067. }
  64068. var engine = this.getScene().getEngine();
  64069. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64070. bilinearFiltering: bilinearFiltering,
  64071. comparisonFunction: comparisonFunction,
  64072. generateStencil: generateStencil,
  64073. isCube: this.isCube
  64074. });
  64075. engine.setFrameBufferDepthStencilTexture(this);
  64076. };
  64077. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64078. if (size.ratio) {
  64079. this._sizeRatio = size.ratio;
  64080. this._size = {
  64081. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64082. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64083. };
  64084. }
  64085. else {
  64086. this._size = size;
  64087. }
  64088. };
  64089. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64090. get: function () {
  64091. return this._samples;
  64092. },
  64093. set: function (value) {
  64094. if (this._samples === value) {
  64095. return;
  64096. }
  64097. var scene = this.getScene();
  64098. if (!scene) {
  64099. return;
  64100. }
  64101. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64102. },
  64103. enumerable: true,
  64104. configurable: true
  64105. });
  64106. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64107. this._currentRefreshId = -1;
  64108. };
  64109. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64110. get: function () {
  64111. return this._refreshRate;
  64112. },
  64113. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64114. set: function (value) {
  64115. this._refreshRate = value;
  64116. this.resetRefreshCounter();
  64117. },
  64118. enumerable: true,
  64119. configurable: true
  64120. });
  64121. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64122. if (!this._postProcessManager) {
  64123. var scene = this.getScene();
  64124. if (!scene) {
  64125. return;
  64126. }
  64127. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64128. this._postProcesses = new Array();
  64129. }
  64130. this._postProcesses.push(postProcess);
  64131. this._postProcesses[0].autoClear = false;
  64132. };
  64133. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64134. if (!this._postProcesses) {
  64135. return;
  64136. }
  64137. if (dispose) {
  64138. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64139. var postProcess = _a[_i];
  64140. postProcess.dispose();
  64141. }
  64142. }
  64143. this._postProcesses = [];
  64144. };
  64145. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64146. if (!this._postProcesses) {
  64147. return;
  64148. }
  64149. var index = this._postProcesses.indexOf(postProcess);
  64150. if (index === -1) {
  64151. return;
  64152. }
  64153. this._postProcesses.splice(index, 1);
  64154. if (this._postProcesses.length > 0) {
  64155. this._postProcesses[0].autoClear = false;
  64156. }
  64157. };
  64158. RenderTargetTexture.prototype._shouldRender = function () {
  64159. if (this._currentRefreshId === -1) { // At least render once
  64160. this._currentRefreshId = 1;
  64161. return true;
  64162. }
  64163. if (this.refreshRate === this._currentRefreshId) {
  64164. this._currentRefreshId = 1;
  64165. return true;
  64166. }
  64167. this._currentRefreshId++;
  64168. return false;
  64169. };
  64170. RenderTargetTexture.prototype.getRenderSize = function () {
  64171. if (this._size.width) {
  64172. return this._size.width;
  64173. }
  64174. return this._size;
  64175. };
  64176. RenderTargetTexture.prototype.getRenderWidth = function () {
  64177. if (this._size.width) {
  64178. return this._size.width;
  64179. }
  64180. return this._size;
  64181. };
  64182. RenderTargetTexture.prototype.getRenderHeight = function () {
  64183. if (this._size.width) {
  64184. return this._size.height;
  64185. }
  64186. return this._size;
  64187. };
  64188. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64189. get: function () {
  64190. return true;
  64191. },
  64192. enumerable: true,
  64193. configurable: true
  64194. });
  64195. RenderTargetTexture.prototype.scale = function (ratio) {
  64196. var newSize = this.getRenderSize() * ratio;
  64197. this.resize(newSize);
  64198. };
  64199. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64200. if (this.isCube) {
  64201. return this._textureMatrix;
  64202. }
  64203. return _super.prototype.getReflectionTextureMatrix.call(this);
  64204. };
  64205. RenderTargetTexture.prototype.resize = function (size) {
  64206. this.releaseInternalTexture();
  64207. var scene = this.getScene();
  64208. if (!scene) {
  64209. return;
  64210. }
  64211. this._processSizeParameter(size);
  64212. if (this.isCube) {
  64213. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64214. }
  64215. else {
  64216. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64217. }
  64218. };
  64219. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64220. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64221. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64222. var scene = this.getScene();
  64223. if (!scene) {
  64224. return;
  64225. }
  64226. var engine = scene.getEngine();
  64227. if (this.useCameraPostProcesses !== undefined) {
  64228. useCameraPostProcess = this.useCameraPostProcesses;
  64229. }
  64230. if (this._waitingRenderList) {
  64231. this.renderList = [];
  64232. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64233. var id = this._waitingRenderList[index];
  64234. var mesh_1 = scene.getMeshByID(id);
  64235. if (mesh_1) {
  64236. this.renderList.push(mesh_1);
  64237. }
  64238. }
  64239. delete this._waitingRenderList;
  64240. }
  64241. // Is predicate defined?
  64242. if (this.renderListPredicate) {
  64243. if (this.renderList) {
  64244. this.renderList.splice(0); // Clear previous renderList
  64245. }
  64246. else {
  64247. this.renderList = [];
  64248. }
  64249. var scene = this.getScene();
  64250. if (!scene) {
  64251. return;
  64252. }
  64253. var sceneMeshes = scene.meshes;
  64254. for (var index = 0; index < sceneMeshes.length; index++) {
  64255. var mesh = sceneMeshes[index];
  64256. if (this.renderListPredicate(mesh)) {
  64257. this.renderList.push(mesh);
  64258. }
  64259. }
  64260. }
  64261. this.onBeforeBindObservable.notifyObservers(this);
  64262. // Set custom projection.
  64263. // Needs to be before binding to prevent changing the aspect ratio.
  64264. var camera;
  64265. if (this.activeCamera) {
  64266. camera = this.activeCamera;
  64267. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64268. if (this.activeCamera !== scene.activeCamera) {
  64269. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64270. }
  64271. }
  64272. else {
  64273. camera = scene.activeCamera;
  64274. if (camera) {
  64275. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64276. }
  64277. }
  64278. // Prepare renderingManager
  64279. this._renderingManager.reset();
  64280. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64281. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64282. var sceneRenderId = scene.getRenderId();
  64283. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64284. var mesh = currentRenderList[meshIndex];
  64285. if (mesh) {
  64286. if (!mesh.isReady(this.refreshRate === 0)) {
  64287. this.resetRefreshCounter();
  64288. continue;
  64289. }
  64290. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64291. var isMasked = void 0;
  64292. if (!this.renderList && camera) {
  64293. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64294. }
  64295. else {
  64296. isMasked = false;
  64297. }
  64298. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64299. mesh._activate(sceneRenderId);
  64300. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64301. var subMesh = mesh.subMeshes[subIndex];
  64302. scene._activeIndices.addCount(subMesh.indexCount, false);
  64303. this._renderingManager.dispatch(subMesh, mesh);
  64304. }
  64305. }
  64306. }
  64307. }
  64308. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64309. var particleSystem = scene.particleSystems[particleIndex];
  64310. var emitter = particleSystem.emitter;
  64311. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64312. continue;
  64313. }
  64314. if (currentRenderList.indexOf(emitter) >= 0) {
  64315. this._renderingManager.dispatchParticles(particleSystem);
  64316. }
  64317. }
  64318. if (this.isCube) {
  64319. for (var face = 0; face < 6; face++) {
  64320. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64321. scene.incrementRenderId();
  64322. scene.resetCachedMaterial();
  64323. }
  64324. }
  64325. else {
  64326. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64327. }
  64328. this.onAfterUnbindObservable.notifyObservers(this);
  64329. if (scene.activeCamera) {
  64330. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64331. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64332. }
  64333. engine.setViewport(scene.activeCamera.viewport);
  64334. }
  64335. scene.resetCachedMaterial();
  64336. };
  64337. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64338. var minimum = 128;
  64339. var x = renderDimension * scale;
  64340. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64341. // Ensure we don't exceed the render dimension (while staying POT)
  64342. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64343. };
  64344. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64345. var _this = this;
  64346. if (!this._texture) {
  64347. return;
  64348. }
  64349. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64350. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64351. });
  64352. };
  64353. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64354. var scene = this.getScene();
  64355. if (!scene) {
  64356. return;
  64357. }
  64358. var engine = scene.getEngine();
  64359. if (!this._texture) {
  64360. return;
  64361. }
  64362. // Bind
  64363. if (this._postProcessManager) {
  64364. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64365. }
  64366. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64367. if (this._texture) {
  64368. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64369. }
  64370. }
  64371. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64372. // Clear
  64373. if (this.onClearObservable.hasObservers()) {
  64374. this.onClearObservable.notifyObservers(engine);
  64375. }
  64376. else {
  64377. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64378. }
  64379. if (!this._doNotChangeAspectRatio) {
  64380. scene.updateTransformMatrix(true);
  64381. }
  64382. // Render
  64383. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64384. if (this._postProcessManager) {
  64385. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64386. }
  64387. else if (useCameraPostProcess) {
  64388. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64389. }
  64390. if (!this._doNotChangeAspectRatio) {
  64391. scene.updateTransformMatrix(true);
  64392. }
  64393. // Dump ?
  64394. if (dumpForDebug) {
  64395. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64396. }
  64397. // Unbind
  64398. if (!this.isCube || faceIndex === 5) {
  64399. if (this.isCube) {
  64400. if (faceIndex === 5) {
  64401. engine.generateMipMapsForCubemap(this._texture);
  64402. }
  64403. }
  64404. this.unbindFrameBuffer(engine, faceIndex);
  64405. }
  64406. else {
  64407. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64408. }
  64409. };
  64410. /**
  64411. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64412. * This allowed control for front to back rendering or reversly depending of the special needs.
  64413. *
  64414. * @param renderingGroupId The rendering group id corresponding to its index
  64415. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64416. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64417. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64418. */
  64419. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64420. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64421. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64422. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64423. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64424. };
  64425. /**
  64426. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64427. *
  64428. * @param renderingGroupId The rendering group id corresponding to its index
  64429. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64430. */
  64431. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64432. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64433. };
  64434. RenderTargetTexture.prototype.clone = function () {
  64435. var textureSize = this.getSize();
  64436. 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);
  64437. // Base texture
  64438. newTexture.hasAlpha = this.hasAlpha;
  64439. newTexture.level = this.level;
  64440. // RenderTarget Texture
  64441. newTexture.coordinatesMode = this.coordinatesMode;
  64442. if (this.renderList) {
  64443. newTexture.renderList = this.renderList.slice(0);
  64444. }
  64445. return newTexture;
  64446. };
  64447. RenderTargetTexture.prototype.serialize = function () {
  64448. if (!this.name) {
  64449. return null;
  64450. }
  64451. var serializationObject = _super.prototype.serialize.call(this);
  64452. serializationObject.renderTargetSize = this.getRenderSize();
  64453. serializationObject.renderList = [];
  64454. if (this.renderList) {
  64455. for (var index = 0; index < this.renderList.length; index++) {
  64456. serializationObject.renderList.push(this.renderList[index].id);
  64457. }
  64458. }
  64459. return serializationObject;
  64460. };
  64461. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64462. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64463. var objBuffer = this.getInternalTexture();
  64464. var scene = this.getScene();
  64465. if (objBuffer && scene) {
  64466. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64467. }
  64468. };
  64469. RenderTargetTexture.prototype.dispose = function () {
  64470. if (this._postProcessManager) {
  64471. this._postProcessManager.dispose();
  64472. this._postProcessManager = null;
  64473. }
  64474. this.clearPostProcesses(true);
  64475. if (this._resizeObserver) {
  64476. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64477. this._resizeObserver = null;
  64478. }
  64479. this.renderList = null;
  64480. // Remove from custom render targets
  64481. var scene = this.getScene();
  64482. if (!scene) {
  64483. return;
  64484. }
  64485. var index = scene.customRenderTargets.indexOf(this);
  64486. if (index >= 0) {
  64487. scene.customRenderTargets.splice(index, 1);
  64488. }
  64489. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64490. var camera = _a[_i];
  64491. index = camera.customRenderTargets.indexOf(this);
  64492. if (index >= 0) {
  64493. camera.customRenderTargets.splice(index, 1);
  64494. }
  64495. }
  64496. _super.prototype.dispose.call(this);
  64497. };
  64498. RenderTargetTexture.prototype._rebuild = function () {
  64499. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64500. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64501. }
  64502. if (this._postProcessManager) {
  64503. this._postProcessManager._rebuild();
  64504. }
  64505. };
  64506. /**
  64507. * Clear the info related to rendering groups preventing retention point in material dispose.
  64508. */
  64509. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64510. if (this._renderingManager) {
  64511. this._renderingManager.freeRenderingGroups();
  64512. }
  64513. };
  64514. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64515. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64516. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64517. return RenderTargetTexture;
  64518. }(BABYLON.Texture));
  64519. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64520. })(BABYLON || (BABYLON = {}));
  64521. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64522. var BABYLON;
  64523. (function (BABYLON) {
  64524. ;
  64525. var MultiRenderTarget = /** @class */ (function (_super) {
  64526. __extends(MultiRenderTarget, _super);
  64527. function MultiRenderTarget(name, size, count, scene, options) {
  64528. var _this = this;
  64529. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64530. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64531. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64532. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64533. _this._engine = scene.getEngine();
  64534. if (!_this.isSupported) {
  64535. _this.dispose();
  64536. return;
  64537. }
  64538. var types = [];
  64539. var samplingModes = [];
  64540. for (var i = 0; i < count; i++) {
  64541. if (options && options.types && options.types[i] !== undefined) {
  64542. types.push(options.types[i]);
  64543. }
  64544. else {
  64545. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64546. }
  64547. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64548. samplingModes.push(options.samplingModes[i]);
  64549. }
  64550. else {
  64551. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64552. }
  64553. }
  64554. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64555. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64556. _this._size = size;
  64557. _this._multiRenderTargetOptions = {
  64558. samplingModes: samplingModes,
  64559. generateMipMaps: generateMipMaps,
  64560. generateDepthBuffer: generateDepthBuffer,
  64561. generateStencilBuffer: generateStencilBuffer,
  64562. generateDepthTexture: generateDepthTexture,
  64563. types: types,
  64564. textureCount: count
  64565. };
  64566. _this._createInternalTextures();
  64567. _this._createTextures();
  64568. return _this;
  64569. }
  64570. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64571. get: function () {
  64572. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64573. },
  64574. enumerable: true,
  64575. configurable: true
  64576. });
  64577. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64578. get: function () {
  64579. return this._textures;
  64580. },
  64581. enumerable: true,
  64582. configurable: true
  64583. });
  64584. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64585. get: function () {
  64586. return this._textures[this._textures.length - 1];
  64587. },
  64588. enumerable: true,
  64589. configurable: true
  64590. });
  64591. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64592. set: function (wrap) {
  64593. if (this._textures) {
  64594. for (var i = 0; i < this._textures.length; i++) {
  64595. this._textures[i].wrapU = wrap;
  64596. }
  64597. }
  64598. },
  64599. enumerable: true,
  64600. configurable: true
  64601. });
  64602. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64603. set: function (wrap) {
  64604. if (this._textures) {
  64605. for (var i = 0; i < this._textures.length; i++) {
  64606. this._textures[i].wrapV = wrap;
  64607. }
  64608. }
  64609. },
  64610. enumerable: true,
  64611. configurable: true
  64612. });
  64613. MultiRenderTarget.prototype._rebuild = function () {
  64614. this.releaseInternalTextures();
  64615. this._createInternalTextures();
  64616. for (var i = 0; i < this._internalTextures.length; i++) {
  64617. var texture = this._textures[i];
  64618. texture._texture = this._internalTextures[i];
  64619. }
  64620. // Keeps references to frame buffer and stencil/depth buffer
  64621. this._texture = this._internalTextures[0];
  64622. };
  64623. MultiRenderTarget.prototype._createInternalTextures = function () {
  64624. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64625. };
  64626. MultiRenderTarget.prototype._createTextures = function () {
  64627. this._textures = [];
  64628. for (var i = 0; i < this._internalTextures.length; i++) {
  64629. var texture = new BABYLON.Texture(null, this.getScene());
  64630. texture._texture = this._internalTextures[i];
  64631. this._textures.push(texture);
  64632. }
  64633. // Keeps references to frame buffer and stencil/depth buffer
  64634. this._texture = this._internalTextures[0];
  64635. };
  64636. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64637. get: function () {
  64638. return this._samples;
  64639. },
  64640. set: function (value) {
  64641. if (this._samples === value) {
  64642. return;
  64643. }
  64644. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64645. },
  64646. enumerable: true,
  64647. configurable: true
  64648. });
  64649. MultiRenderTarget.prototype.resize = function (size) {
  64650. this.releaseInternalTextures();
  64651. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64652. this._createInternalTextures();
  64653. };
  64654. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64655. var _this = this;
  64656. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64657. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64658. });
  64659. };
  64660. MultiRenderTarget.prototype.dispose = function () {
  64661. this.releaseInternalTextures();
  64662. _super.prototype.dispose.call(this);
  64663. };
  64664. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64665. if (!this._internalTextures) {
  64666. return;
  64667. }
  64668. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64669. if (this._internalTextures[i] !== undefined) {
  64670. this._internalTextures[i].dispose();
  64671. this._internalTextures.splice(i, 1);
  64672. }
  64673. }
  64674. };
  64675. return MultiRenderTarget;
  64676. }(BABYLON.RenderTargetTexture));
  64677. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64678. })(BABYLON || (BABYLON = {}));
  64679. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64680. var BABYLON;
  64681. (function (BABYLON) {
  64682. var MirrorTexture = /** @class */ (function (_super) {
  64683. __extends(MirrorTexture, _super);
  64684. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64685. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64687. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64688. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64689. _this.scene = scene;
  64690. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64691. _this._transformMatrix = BABYLON.Matrix.Zero();
  64692. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64693. _this._adaptiveBlurKernel = 0;
  64694. _this._blurKernelX = 0;
  64695. _this._blurKernelY = 0;
  64696. _this._blurRatio = 1.0;
  64697. _this.ignoreCameraViewport = true;
  64698. _this._updateGammaSpace();
  64699. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64700. _this._updateGammaSpace;
  64701. });
  64702. _this.onBeforeRenderObservable.add(function () {
  64703. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64704. _this._savedViewMatrix = scene.getViewMatrix();
  64705. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64706. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64707. scene.clipPlane = _this.mirrorPlane;
  64708. scene.getEngine().cullBackFaces = false;
  64709. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64710. });
  64711. _this.onAfterRenderObservable.add(function () {
  64712. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64713. scene.getEngine().cullBackFaces = true;
  64714. scene._mirroredCameraPosition = null;
  64715. delete scene.clipPlane;
  64716. });
  64717. return _this;
  64718. }
  64719. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64720. get: function () {
  64721. return this._blurRatio;
  64722. },
  64723. set: function (value) {
  64724. if (this._blurRatio === value) {
  64725. return;
  64726. }
  64727. this._blurRatio = value;
  64728. this._preparePostProcesses();
  64729. },
  64730. enumerable: true,
  64731. configurable: true
  64732. });
  64733. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64734. set: function (value) {
  64735. this._adaptiveBlurKernel = value;
  64736. this._autoComputeBlurKernel();
  64737. },
  64738. enumerable: true,
  64739. configurable: true
  64740. });
  64741. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64742. set: function (value) {
  64743. this.blurKernelX = value;
  64744. this.blurKernelY = value;
  64745. },
  64746. enumerable: true,
  64747. configurable: true
  64748. });
  64749. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64750. get: function () {
  64751. return this._blurKernelX;
  64752. },
  64753. set: function (value) {
  64754. if (this._blurKernelX === value) {
  64755. return;
  64756. }
  64757. this._blurKernelX = value;
  64758. this._preparePostProcesses();
  64759. },
  64760. enumerable: true,
  64761. configurable: true
  64762. });
  64763. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64764. get: function () {
  64765. return this._blurKernelY;
  64766. },
  64767. set: function (value) {
  64768. if (this._blurKernelY === value) {
  64769. return;
  64770. }
  64771. this._blurKernelY = value;
  64772. this._preparePostProcesses();
  64773. },
  64774. enumerable: true,
  64775. configurable: true
  64776. });
  64777. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64778. var engine = this.getScene().getEngine();
  64779. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64780. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64781. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64782. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64783. };
  64784. MirrorTexture.prototype._onRatioRescale = function () {
  64785. if (this._sizeRatio) {
  64786. this.resize(this._initialSizeParameter);
  64787. if (!this._adaptiveBlurKernel) {
  64788. this._preparePostProcesses();
  64789. }
  64790. }
  64791. if (this._adaptiveBlurKernel) {
  64792. this._autoComputeBlurKernel();
  64793. }
  64794. };
  64795. MirrorTexture.prototype._updateGammaSpace = function () {
  64796. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64797. };
  64798. MirrorTexture.prototype._preparePostProcesses = function () {
  64799. this.clearPostProcesses(true);
  64800. if (this._blurKernelX && this._blurKernelY) {
  64801. var engine = this.getScene().getEngine();
  64802. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64803. 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);
  64804. this._blurX.autoClear = false;
  64805. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64806. this._blurX.inputTexture = this._texture;
  64807. }
  64808. else {
  64809. this._blurX.alwaysForcePOT = true;
  64810. }
  64811. 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);
  64812. this._blurY.autoClear = false;
  64813. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64814. this.addPostProcess(this._blurX);
  64815. this.addPostProcess(this._blurY);
  64816. }
  64817. else {
  64818. if (this._blurY) {
  64819. this.removePostProcess(this._blurY);
  64820. this._blurY.dispose();
  64821. this._blurY = null;
  64822. }
  64823. if (this._blurX) {
  64824. this.removePostProcess(this._blurX);
  64825. this._blurX.dispose();
  64826. this._blurX = null;
  64827. }
  64828. }
  64829. };
  64830. MirrorTexture.prototype.clone = function () {
  64831. var scene = this.getScene();
  64832. if (!scene) {
  64833. return this;
  64834. }
  64835. var textureSize = this.getSize();
  64836. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64837. // Base texture
  64838. newTexture.hasAlpha = this.hasAlpha;
  64839. newTexture.level = this.level;
  64840. // Mirror Texture
  64841. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64842. if (this.renderList) {
  64843. newTexture.renderList = this.renderList.slice(0);
  64844. }
  64845. return newTexture;
  64846. };
  64847. MirrorTexture.prototype.serialize = function () {
  64848. if (!this.name) {
  64849. return null;
  64850. }
  64851. var serializationObject = _super.prototype.serialize.call(this);
  64852. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64853. return serializationObject;
  64854. };
  64855. MirrorTexture.prototype.dispose = function () {
  64856. _super.prototype.dispose.call(this);
  64857. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64858. };
  64859. return MirrorTexture;
  64860. }(BABYLON.RenderTargetTexture));
  64861. BABYLON.MirrorTexture = MirrorTexture;
  64862. })(BABYLON || (BABYLON = {}));
  64863. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64864. var BABYLON;
  64865. (function (BABYLON) {
  64866. /**
  64867. * Creates a refraction texture used by refraction channel of the standard material.
  64868. * @param name the texture name
  64869. * @param size size of the underlying texture
  64870. * @param scene root scene
  64871. */
  64872. var RefractionTexture = /** @class */ (function (_super) {
  64873. __extends(RefractionTexture, _super);
  64874. function RefractionTexture(name, size, scene, generateMipMaps) {
  64875. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64876. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64877. _this.depth = 2.0;
  64878. _this.onBeforeRenderObservable.add(function () {
  64879. scene.clipPlane = _this.refractionPlane;
  64880. });
  64881. _this.onAfterRenderObservable.add(function () {
  64882. delete scene.clipPlane;
  64883. });
  64884. return _this;
  64885. }
  64886. RefractionTexture.prototype.clone = function () {
  64887. var scene = this.getScene();
  64888. if (!scene) {
  64889. return this;
  64890. }
  64891. var textureSize = this.getSize();
  64892. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64893. // Base texture
  64894. newTexture.hasAlpha = this.hasAlpha;
  64895. newTexture.level = this.level;
  64896. // Refraction Texture
  64897. newTexture.refractionPlane = this.refractionPlane.clone();
  64898. if (this.renderList) {
  64899. newTexture.renderList = this.renderList.slice(0);
  64900. }
  64901. newTexture.depth = this.depth;
  64902. return newTexture;
  64903. };
  64904. RefractionTexture.prototype.serialize = function () {
  64905. if (!this.name) {
  64906. return null;
  64907. }
  64908. var serializationObject = _super.prototype.serialize.call(this);
  64909. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64910. serializationObject.depth = this.depth;
  64911. return serializationObject;
  64912. };
  64913. return RefractionTexture;
  64914. }(BABYLON.RenderTargetTexture));
  64915. BABYLON.RefractionTexture = RefractionTexture;
  64916. })(BABYLON || (BABYLON = {}));
  64917. //# sourceMappingURL=babylon.refractionTexture.js.map
  64918. var BABYLON;
  64919. (function (BABYLON) {
  64920. /**
  64921. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64922. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64923. */
  64924. var DynamicTexture = /** @class */ (function (_super) {
  64925. __extends(DynamicTexture, _super);
  64926. /**
  64927. * Creates a {BABYLON.DynamicTexture}
  64928. * @param name defines the name of the texture
  64929. * @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
  64930. * @param scene defines the scene where you want the texture
  64931. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64932. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64933. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64934. */
  64935. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64936. if (scene === void 0) { scene = null; }
  64937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64938. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64939. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64940. _this.name = name;
  64941. _this._engine = _this.getScene().getEngine();
  64942. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64943. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64944. _this._generateMipMaps = generateMipMaps;
  64945. if (options.getContext) {
  64946. _this._canvas = options;
  64947. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64948. }
  64949. else {
  64950. _this._canvas = document.createElement("canvas");
  64951. if (options.width || options.width === 0) {
  64952. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64953. }
  64954. else {
  64955. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64956. }
  64957. }
  64958. var textureSize = _this.getSize();
  64959. _this._canvas.width = textureSize.width;
  64960. _this._canvas.height = textureSize.height;
  64961. _this._context = _this._canvas.getContext("2d");
  64962. return _this;
  64963. }
  64964. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64965. /**
  64966. * Gets the current state of canRescale
  64967. */
  64968. get: function () {
  64969. return true;
  64970. },
  64971. enumerable: true,
  64972. configurable: true
  64973. });
  64974. DynamicTexture.prototype._recreate = function (textureSize) {
  64975. this._canvas.width = textureSize.width;
  64976. this._canvas.height = textureSize.height;
  64977. this.releaseInternalTexture();
  64978. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64979. };
  64980. /**
  64981. * Scales the texture
  64982. * @param ratio the scale factor to apply to both width and height
  64983. */
  64984. DynamicTexture.prototype.scale = function (ratio) {
  64985. var textureSize = this.getSize();
  64986. textureSize.width *= ratio;
  64987. textureSize.height *= ratio;
  64988. this._recreate(textureSize);
  64989. };
  64990. /**
  64991. * Resizes the texture
  64992. * @param width the new width
  64993. * @param height the new height
  64994. */
  64995. DynamicTexture.prototype.scaleTo = function (width, height) {
  64996. var textureSize = this.getSize();
  64997. textureSize.width = width;
  64998. textureSize.height = height;
  64999. this._recreate(textureSize);
  65000. };
  65001. /**
  65002. * Gets the context of the canvas used by the texture
  65003. * @returns the canvas context of the dynamic texture
  65004. */
  65005. DynamicTexture.prototype.getContext = function () {
  65006. return this._context;
  65007. };
  65008. /**
  65009. * Clears the texture
  65010. */
  65011. DynamicTexture.prototype.clear = function () {
  65012. var size = this.getSize();
  65013. this._context.fillRect(0, 0, size.width, size.height);
  65014. };
  65015. /**
  65016. * Updates the texture
  65017. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65018. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65019. */
  65020. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65021. if (premulAlpha === void 0) { premulAlpha = false; }
  65022. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65023. };
  65024. /**
  65025. * Draws text onto the texture
  65026. * @param text defines the text to be drawn
  65027. * @param x defines the placement of the text from the left
  65028. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65029. * @param font defines the font to be used with font-style, font-size, font-name
  65030. * @param color defines the color used for the text
  65031. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65032. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65033. * @param update defines whether texture is immediately update (default is true)
  65034. */
  65035. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65036. if (update === void 0) { update = true; }
  65037. var size = this.getSize();
  65038. if (clearColor) {
  65039. this._context.fillStyle = clearColor;
  65040. this._context.fillRect(0, 0, size.width, size.height);
  65041. }
  65042. this._context.font = font;
  65043. if (x === null || x === undefined) {
  65044. var textSize = this._context.measureText(text);
  65045. x = (size.width - textSize.width) / 2;
  65046. }
  65047. if (y === null || y === undefined) {
  65048. var fontSize = parseInt((font.replace(/\D/g, '')));
  65049. y = (size.height / 2) + (fontSize / 3.65);
  65050. }
  65051. this._context.fillStyle = color;
  65052. this._context.fillText(text, x, y);
  65053. if (update) {
  65054. this.update(invertY);
  65055. }
  65056. };
  65057. /**
  65058. * Clones the texture
  65059. * @returns the clone of the texture.
  65060. */
  65061. DynamicTexture.prototype.clone = function () {
  65062. var scene = this.getScene();
  65063. if (!scene) {
  65064. return this;
  65065. }
  65066. var textureSize = this.getSize();
  65067. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65068. // Base texture
  65069. newTexture.hasAlpha = this.hasAlpha;
  65070. newTexture.level = this.level;
  65071. // Dynamic Texture
  65072. newTexture.wrapU = this.wrapU;
  65073. newTexture.wrapV = this.wrapV;
  65074. return newTexture;
  65075. };
  65076. /** @hidden */
  65077. DynamicTexture.prototype._rebuild = function () {
  65078. this.update();
  65079. };
  65080. return DynamicTexture;
  65081. }(BABYLON.Texture));
  65082. BABYLON.DynamicTexture = DynamicTexture;
  65083. })(BABYLON || (BABYLON = {}));
  65084. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65085. var BABYLON;
  65086. (function (BABYLON) {
  65087. var VideoTexture = /** @class */ (function (_super) {
  65088. __extends(VideoTexture, _super);
  65089. /**
  65090. * Creates a video texture.
  65091. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65092. * @param {string | null} name optional name, will detect from video source, if not defined
  65093. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65094. * @param {BABYLON.Scene} scene is obviously the current scene.
  65095. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65096. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65097. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65098. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65099. */
  65100. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65101. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65102. if (invertY === void 0) { invertY = false; }
  65103. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65104. if (settings === void 0) { settings = {
  65105. autoPlay: true,
  65106. loop: true,
  65107. autoUpdateTexture: true,
  65108. }; }
  65109. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65110. _this._onUserActionRequestedObservable = null;
  65111. _this._stillImageCaptured = false;
  65112. _this._createInternalTexture = function () {
  65113. if (_this._texture != null) {
  65114. return;
  65115. }
  65116. if (!_this._engine.needPOTTextures ||
  65117. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65118. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65119. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65120. }
  65121. else {
  65122. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65123. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65124. _this._generateMipMaps = false;
  65125. }
  65126. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65127. if (!_this.video.autoplay) {
  65128. var oldHandler_1 = _this.video.onplaying;
  65129. var error_1 = false;
  65130. _this.video.onplaying = function () {
  65131. _this.video.onplaying = oldHandler_1;
  65132. _this._texture.isReady = true;
  65133. _this._updateInternalTexture();
  65134. if (!error_1) {
  65135. _this.video.pause();
  65136. }
  65137. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65138. _this.onLoadObservable.notifyObservers(_this);
  65139. }
  65140. };
  65141. var playing = _this.video.play();
  65142. if (playing) {
  65143. playing.then(function () {
  65144. // Everything is good.
  65145. })
  65146. .catch(function () {
  65147. error_1 = true;
  65148. // On Chrome for instance, new policies might prevent playing without user interaction.
  65149. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  65150. _this._onUserActionRequestedObservable.notifyObservers(_this);
  65151. }
  65152. });
  65153. }
  65154. else {
  65155. _this.video.onplaying = oldHandler_1;
  65156. _this._texture.isReady = true;
  65157. _this._updateInternalTexture();
  65158. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65159. _this.onLoadObservable.notifyObservers(_this);
  65160. }
  65161. }
  65162. }
  65163. else {
  65164. _this._texture.isReady = true;
  65165. _this._updateInternalTexture();
  65166. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65167. _this.onLoadObservable.notifyObservers(_this);
  65168. }
  65169. }
  65170. };
  65171. _this.reset = function () {
  65172. if (_this._texture == null) {
  65173. return;
  65174. }
  65175. _this._texture.dispose();
  65176. _this._texture = null;
  65177. };
  65178. _this._updateInternalTexture = function (e) {
  65179. if (_this._texture == null || !_this._texture.isReady) {
  65180. return;
  65181. }
  65182. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65183. return;
  65184. }
  65185. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65186. };
  65187. _this._engine = _this.getScene().getEngine();
  65188. _this._generateMipMaps = generateMipMaps;
  65189. _this._samplingMode = samplingMode;
  65190. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65191. _this.name = name || _this._getName(src);
  65192. _this.video = _this._getVideo(src);
  65193. if (settings.poster) {
  65194. _this.video.poster = settings.poster;
  65195. }
  65196. if (settings.autoPlay !== undefined) {
  65197. _this.video.autoplay = settings.autoPlay;
  65198. }
  65199. if (settings.loop !== undefined) {
  65200. _this.video.loop = settings.loop;
  65201. }
  65202. _this.video.setAttribute("playsinline", "");
  65203. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65204. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65205. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65206. _this.video.addEventListener("emptied", _this.reset);
  65207. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65208. _this._createInternalTexture();
  65209. }
  65210. return _this;
  65211. }
  65212. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  65213. get: function () {
  65214. if (!this._onUserActionRequestedObservable) {
  65215. this._onUserActionRequestedObservable = new BABYLON.Observable();
  65216. }
  65217. return this._onUserActionRequestedObservable;
  65218. },
  65219. enumerable: true,
  65220. configurable: true
  65221. });
  65222. VideoTexture.prototype._getName = function (src) {
  65223. if (src instanceof HTMLVideoElement) {
  65224. return src.currentSrc;
  65225. }
  65226. if (typeof src === "object") {
  65227. return src.toString();
  65228. }
  65229. return src;
  65230. };
  65231. ;
  65232. VideoTexture.prototype._getVideo = function (src) {
  65233. if (src instanceof HTMLVideoElement) {
  65234. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65235. return src;
  65236. }
  65237. var video = document.createElement("video");
  65238. if (typeof src === "string") {
  65239. BABYLON.Tools.SetCorsBehavior(src, video);
  65240. video.src = src;
  65241. }
  65242. else {
  65243. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65244. src.forEach(function (url) {
  65245. var source = document.createElement("source");
  65246. source.src = url;
  65247. video.appendChild(source);
  65248. });
  65249. }
  65250. return video;
  65251. };
  65252. ;
  65253. /**
  65254. * Internal method to initiate `update`.
  65255. */
  65256. VideoTexture.prototype._rebuild = function () {
  65257. this.update();
  65258. };
  65259. /**
  65260. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65261. */
  65262. VideoTexture.prototype.update = function () {
  65263. if (!this.autoUpdateTexture) {
  65264. // Expecting user to call `updateTexture` manually
  65265. return;
  65266. }
  65267. this.updateTexture(true);
  65268. };
  65269. /**
  65270. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65271. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65272. */
  65273. VideoTexture.prototype.updateTexture = function (isVisible) {
  65274. if (!isVisible) {
  65275. return;
  65276. }
  65277. if (this.video.paused && this._stillImageCaptured) {
  65278. return;
  65279. }
  65280. this._stillImageCaptured = true;
  65281. this._updateInternalTexture();
  65282. };
  65283. /**
  65284. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65285. * @param url New url.
  65286. */
  65287. VideoTexture.prototype.updateURL = function (url) {
  65288. this.video.src = url;
  65289. };
  65290. VideoTexture.prototype.dispose = function () {
  65291. _super.prototype.dispose.call(this);
  65292. if (this._onUserActionRequestedObservable) {
  65293. this._onUserActionRequestedObservable.clear();
  65294. this._onUserActionRequestedObservable = null;
  65295. }
  65296. this.video.removeEventListener("canplay", this._createInternalTexture);
  65297. this.video.removeEventListener("paused", this._updateInternalTexture);
  65298. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65299. this.video.removeEventListener("emptied", this.reset);
  65300. this.video.pause();
  65301. };
  65302. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65303. var video = document.createElement("video");
  65304. video.setAttribute('autoplay', '');
  65305. video.setAttribute('muted', '');
  65306. video.setAttribute('playsinline', '');
  65307. var constraintsDeviceId;
  65308. if (constraints && constraints.deviceId) {
  65309. constraintsDeviceId = {
  65310. exact: constraints.deviceId,
  65311. };
  65312. }
  65313. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65314. if (navigator.mediaDevices) {
  65315. navigator.mediaDevices.getUserMedia({ video: constraints })
  65316. .then(function (stream) {
  65317. if (video.mozSrcObject !== undefined) {
  65318. // hack for Firefox < 19
  65319. video.mozSrcObject = stream;
  65320. }
  65321. else {
  65322. video.srcObject = stream;
  65323. }
  65324. var onPlaying = function () {
  65325. if (onReady) {
  65326. onReady(new VideoTexture("video", video, scene, true, true));
  65327. }
  65328. video.removeEventListener("playing", onPlaying);
  65329. };
  65330. video.addEventListener("playing", onPlaying);
  65331. video.play();
  65332. })
  65333. .catch(function (err) {
  65334. BABYLON.Tools.Error(err.name);
  65335. });
  65336. }
  65337. else {
  65338. navigator.getUserMedia =
  65339. navigator.getUserMedia ||
  65340. navigator.webkitGetUserMedia ||
  65341. navigator.mozGetUserMedia ||
  65342. navigator.msGetUserMedia;
  65343. if (navigator.getUserMedia) {
  65344. navigator.getUserMedia({
  65345. video: {
  65346. deviceId: constraintsDeviceId,
  65347. width: {
  65348. min: (constraints && constraints.minWidth) || 256,
  65349. max: (constraints && constraints.maxWidth) || 640,
  65350. },
  65351. height: {
  65352. min: (constraints && constraints.minHeight) || 256,
  65353. max: (constraints && constraints.maxHeight) || 480,
  65354. },
  65355. },
  65356. }, function (stream) {
  65357. if (video.mozSrcObject !== undefined) {
  65358. // hack for Firefox < 19
  65359. video.mozSrcObject = stream;
  65360. }
  65361. else {
  65362. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65363. }
  65364. video.play();
  65365. if (onReady) {
  65366. onReady(new VideoTexture("video", video, scene, true, true));
  65367. }
  65368. }, function (e) {
  65369. BABYLON.Tools.Error(e.name);
  65370. });
  65371. }
  65372. }
  65373. };
  65374. return VideoTexture;
  65375. }(BABYLON.Texture));
  65376. BABYLON.VideoTexture = VideoTexture;
  65377. })(BABYLON || (BABYLON = {}));
  65378. //# sourceMappingURL=babylon.videoTexture.js.map
  65379. var BABYLON;
  65380. (function (BABYLON) {
  65381. var RawTexture = /** @class */ (function (_super) {
  65382. __extends(RawTexture, _super);
  65383. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65384. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65385. if (invertY === void 0) { invertY = false; }
  65386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65387. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65388. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65389. _this.format = format;
  65390. _this._engine = scene.getEngine();
  65391. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65392. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65393. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65394. return _this;
  65395. }
  65396. RawTexture.prototype.update = function (data) {
  65397. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65398. };
  65399. // Statics
  65400. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65401. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65402. if (invertY === void 0) { invertY = false; }
  65403. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65404. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65405. };
  65406. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65407. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65408. if (invertY === void 0) { invertY = false; }
  65409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65410. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65411. };
  65412. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65413. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65414. if (invertY === void 0) { invertY = false; }
  65415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65416. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65417. };
  65418. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65419. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65420. if (invertY === void 0) { invertY = false; }
  65421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65422. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65423. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65424. };
  65425. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65426. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65427. if (invertY === void 0) { invertY = false; }
  65428. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65429. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65430. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65431. };
  65432. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65433. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65434. if (invertY === void 0) { invertY = false; }
  65435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65436. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65437. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65438. };
  65439. return RawTexture;
  65440. }(BABYLON.Texture));
  65441. BABYLON.RawTexture = RawTexture;
  65442. })(BABYLON || (BABYLON = {}));
  65443. //# sourceMappingURL=babylon.rawTexture.js.map
  65444. var BABYLON;
  65445. (function (BABYLON) {
  65446. /**
  65447. * Class used to store 3D textures containing user data
  65448. */
  65449. var RawTexture3D = /** @class */ (function (_super) {
  65450. __extends(RawTexture3D, _super);
  65451. /**
  65452. * Create a new RawTexture3D
  65453. * @param data defines the data of the texture
  65454. * @param width defines the width of the texture
  65455. * @param height defines the height of the texture
  65456. * @param depth defines the depth of the texture
  65457. * @param format defines the texture format to use
  65458. * @param scene defines the hosting scene
  65459. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65460. * @param invertY defines if texture must be stored with Y axis inverted
  65461. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65462. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65463. */
  65464. function RawTexture3D(data, width, height, depth,
  65465. /** Gets or sets the texture format to use */
  65466. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65467. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65468. if (invertY === void 0) { invertY = false; }
  65469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65470. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65471. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65472. _this.format = format;
  65473. _this._engine = scene.getEngine();
  65474. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65475. _this.is3D = true;
  65476. return _this;
  65477. }
  65478. /**
  65479. * Update the texture with new data
  65480. * @param data defines the data to store in the texture
  65481. */
  65482. RawTexture3D.prototype.update = function (data) {
  65483. if (!this._texture) {
  65484. return;
  65485. }
  65486. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65487. };
  65488. return RawTexture3D;
  65489. }(BABYLON.Texture));
  65490. BABYLON.RawTexture3D = RawTexture3D;
  65491. })(BABYLON || (BABYLON = {}));
  65492. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65493. var BABYLON;
  65494. (function (BABYLON) {
  65495. /**
  65496. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65497. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65498. */
  65499. var PostProcessManager = /** @class */ (function () {
  65500. /**
  65501. * Creates a new instance PostProcess
  65502. * @param scene The scene that the post process is associated with.
  65503. */
  65504. function PostProcessManager(scene) {
  65505. this._vertexBuffers = {};
  65506. this._scene = scene;
  65507. }
  65508. PostProcessManager.prototype._prepareBuffers = function () {
  65509. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65510. return;
  65511. }
  65512. // VBO
  65513. var vertices = [];
  65514. vertices.push(1, 1);
  65515. vertices.push(-1, 1);
  65516. vertices.push(-1, -1);
  65517. vertices.push(1, -1);
  65518. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65519. this._buildIndexBuffer();
  65520. };
  65521. PostProcessManager.prototype._buildIndexBuffer = function () {
  65522. // Indices
  65523. var indices = [];
  65524. indices.push(0);
  65525. indices.push(1);
  65526. indices.push(2);
  65527. indices.push(0);
  65528. indices.push(2);
  65529. indices.push(3);
  65530. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65531. };
  65532. /**
  65533. * Rebuilds the vertex buffers of the manager.
  65534. */
  65535. PostProcessManager.prototype._rebuild = function () {
  65536. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65537. if (!vb) {
  65538. return;
  65539. }
  65540. vb._rebuild();
  65541. this._buildIndexBuffer();
  65542. };
  65543. // Methods
  65544. /**
  65545. * Prepares a frame to be run through a post process.
  65546. * @param sourceTexture The input texture to the post procesess. (default: null)
  65547. * @param postProcesses An array of post processes to be run. (default: null)
  65548. * @returns True if the post processes were able to be run.
  65549. */
  65550. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65551. if (sourceTexture === void 0) { sourceTexture = null; }
  65552. if (postProcesses === void 0) { postProcesses = null; }
  65553. var camera = this._scene.activeCamera;
  65554. if (!camera) {
  65555. return false;
  65556. }
  65557. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65558. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65559. return false;
  65560. }
  65561. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65562. return true;
  65563. };
  65564. /**
  65565. * Manually render a set of post processes to a texture.
  65566. * @param postProcesses An array of post processes to be run.
  65567. * @param targetTexture The target texture to render to.
  65568. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65569. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65570. * @param lodLevel defines which lod of the texture to render to
  65571. */
  65572. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65573. if (targetTexture === void 0) { targetTexture = null; }
  65574. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65575. if (faceIndex === void 0) { faceIndex = 0; }
  65576. if (lodLevel === void 0) { lodLevel = 0; }
  65577. var engine = this._scene.getEngine();
  65578. for (var index = 0; index < postProcesses.length; index++) {
  65579. if (index < postProcesses.length - 1) {
  65580. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65581. }
  65582. else {
  65583. if (targetTexture) {
  65584. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65585. }
  65586. else {
  65587. engine.restoreDefaultFramebuffer();
  65588. }
  65589. }
  65590. var pp = postProcesses[index];
  65591. var effect = pp.apply();
  65592. if (effect) {
  65593. pp.onBeforeRenderObservable.notifyObservers(effect);
  65594. // VBOs
  65595. this._prepareBuffers();
  65596. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65597. // Draw order
  65598. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65599. pp.onAfterRenderObservable.notifyObservers(effect);
  65600. }
  65601. }
  65602. // Restore depth buffer
  65603. engine.setDepthBuffer(true);
  65604. engine.setDepthWrite(true);
  65605. };
  65606. /**
  65607. * Finalize the result of the output of the postprocesses.
  65608. * @param doNotPresent If true the result will not be displayed to the screen.
  65609. * @param targetTexture The target texture to render to.
  65610. * @param faceIndex The index of the face to bind the target texture to.
  65611. * @param postProcesses The array of post processes to render.
  65612. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65613. */
  65614. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65615. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65616. var camera = this._scene.activeCamera;
  65617. if (!camera) {
  65618. return;
  65619. }
  65620. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65621. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65622. return;
  65623. }
  65624. var engine = this._scene.getEngine();
  65625. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65626. var pp = postProcesses[index];
  65627. if (index < len - 1) {
  65628. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65629. }
  65630. else {
  65631. if (targetTexture) {
  65632. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65633. pp._outputTexture = targetTexture;
  65634. }
  65635. else {
  65636. engine.restoreDefaultFramebuffer();
  65637. pp._outputTexture = null;
  65638. }
  65639. }
  65640. if (doNotPresent) {
  65641. break;
  65642. }
  65643. var effect = pp.apply();
  65644. if (effect) {
  65645. pp.onBeforeRenderObservable.notifyObservers(effect);
  65646. // VBOs
  65647. this._prepareBuffers();
  65648. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65649. // Draw order
  65650. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65651. pp.onAfterRenderObservable.notifyObservers(effect);
  65652. }
  65653. }
  65654. // Restore states
  65655. engine.setDepthBuffer(true);
  65656. engine.setDepthWrite(true);
  65657. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65658. };
  65659. /**
  65660. * Disposes of the post process manager.
  65661. */
  65662. PostProcessManager.prototype.dispose = function () {
  65663. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65664. if (buffer) {
  65665. buffer.dispose();
  65666. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65667. }
  65668. if (this._indexBuffer) {
  65669. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65670. this._indexBuffer = null;
  65671. }
  65672. };
  65673. return PostProcessManager;
  65674. }());
  65675. BABYLON.PostProcessManager = PostProcessManager;
  65676. })(BABYLON || (BABYLON = {}));
  65677. //# sourceMappingURL=babylon.postProcessManager.js.map
  65678. var BABYLON;
  65679. (function (BABYLON) {
  65680. /**
  65681. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65682. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65683. */
  65684. var PostProcess = /** @class */ (function () {
  65685. /**
  65686. * Creates a new instance PostProcess
  65687. * @param name The name of the PostProcess.
  65688. * @param fragmentUrl The url of the fragment shader to be used.
  65689. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65690. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65691. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65692. * @param camera The camera to apply the render pass to.
  65693. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65694. * @param engine The engine which the post process will be applied. (default: current engine)
  65695. * @param reusable If the post process can be reused on the same frame. (default: false)
  65696. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65697. * @param textureType Type of textures used when performing the post process. (default: 0)
  65698. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65699. * @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
  65700. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65701. */
  65702. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65703. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65704. if (defines === void 0) { defines = null; }
  65705. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65706. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65707. if (blockCompilation === void 0) { blockCompilation = false; }
  65708. this.name = name;
  65709. /**
  65710. * Width of the texture to apply the post process on
  65711. */
  65712. this.width = -1;
  65713. /**
  65714. * Height of the texture to apply the post process on
  65715. */
  65716. this.height = -1;
  65717. /**
  65718. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65719. */
  65720. this._outputTexture = null;
  65721. /**
  65722. * If the buffer needs to be cleared before applying the post process. (default: true)
  65723. * Should be set to false if shader will overwrite all previous pixels.
  65724. */
  65725. this.autoClear = true;
  65726. /**
  65727. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65728. */
  65729. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65730. /**
  65731. * Animations to be used for the post processing
  65732. */
  65733. this.animations = new Array();
  65734. /**
  65735. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65736. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65737. */
  65738. this.enablePixelPerfectMode = false;
  65739. /**
  65740. * Force the postprocess to be applied without taking in account viewport
  65741. */
  65742. this.forceFullscreenViewport = true;
  65743. /**
  65744. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65745. *
  65746. * | Value | Type | Description |
  65747. * | ----- | ----------------------------------- | ----------- |
  65748. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65749. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65750. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65751. *
  65752. */
  65753. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65754. /**
  65755. * Force textures to be a power of two (default: false)
  65756. */
  65757. this.alwaysForcePOT = false;
  65758. /**
  65759. * Number of sample textures (default: 1)
  65760. */
  65761. this.samples = 1;
  65762. /**
  65763. * Modify the scale of the post process to be the same as the viewport (default: false)
  65764. */
  65765. this.adaptScaleToCurrentViewport = false;
  65766. this._reusable = false;
  65767. /**
  65768. * Smart array of input and output textures for the post process.
  65769. */
  65770. this._textures = new BABYLON.SmartArray(2);
  65771. /**
  65772. * The index in _textures that corresponds to the output texture.
  65773. */
  65774. this._currentRenderTextureInd = 0;
  65775. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65776. this._texelSize = BABYLON.Vector2.Zero();
  65777. // Events
  65778. /**
  65779. * An event triggered when the postprocess is activated.
  65780. */
  65781. this.onActivateObservable = new BABYLON.Observable();
  65782. /**
  65783. * An event triggered when the postprocess changes its size.
  65784. */
  65785. this.onSizeChangedObservable = new BABYLON.Observable();
  65786. /**
  65787. * An event triggered when the postprocess applies its effect.
  65788. */
  65789. this.onApplyObservable = new BABYLON.Observable();
  65790. /**
  65791. * An event triggered before rendering the postprocess
  65792. */
  65793. this.onBeforeRenderObservable = new BABYLON.Observable();
  65794. /**
  65795. * An event triggered after rendering the postprocess
  65796. */
  65797. this.onAfterRenderObservable = new BABYLON.Observable();
  65798. if (camera != null) {
  65799. this._camera = camera;
  65800. this._scene = camera.getScene();
  65801. camera.attachPostProcess(this);
  65802. this._engine = this._scene.getEngine();
  65803. this._scene.postProcesses.push(this);
  65804. }
  65805. else if (engine) {
  65806. this._engine = engine;
  65807. this._engine.postProcesses.push(this);
  65808. }
  65809. this._options = options;
  65810. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65811. this._reusable = reusable || false;
  65812. this._textureType = textureType;
  65813. this._samplers = samplers || [];
  65814. this._samplers.push("textureSampler");
  65815. this._fragmentUrl = fragmentUrl;
  65816. this._vertexUrl = vertexUrl;
  65817. this._parameters = parameters || [];
  65818. this._parameters.push("scale");
  65819. this._indexParameters = indexParameters;
  65820. if (!blockCompilation) {
  65821. this.updateEffect(defines);
  65822. }
  65823. }
  65824. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65825. /**
  65826. * A function that is added to the onActivateObservable
  65827. */
  65828. set: function (callback) {
  65829. if (this._onActivateObserver) {
  65830. this.onActivateObservable.remove(this._onActivateObserver);
  65831. }
  65832. if (callback) {
  65833. this._onActivateObserver = this.onActivateObservable.add(callback);
  65834. }
  65835. },
  65836. enumerable: true,
  65837. configurable: true
  65838. });
  65839. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65840. /**
  65841. * A function that is added to the onSizeChangedObservable
  65842. */
  65843. set: function (callback) {
  65844. if (this._onSizeChangedObserver) {
  65845. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65846. }
  65847. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65848. },
  65849. enumerable: true,
  65850. configurable: true
  65851. });
  65852. Object.defineProperty(PostProcess.prototype, "onApply", {
  65853. /**
  65854. * A function that is added to the onApplyObservable
  65855. */
  65856. set: function (callback) {
  65857. if (this._onApplyObserver) {
  65858. this.onApplyObservable.remove(this._onApplyObserver);
  65859. }
  65860. this._onApplyObserver = this.onApplyObservable.add(callback);
  65861. },
  65862. enumerable: true,
  65863. configurable: true
  65864. });
  65865. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65866. /**
  65867. * A function that is added to the onBeforeRenderObservable
  65868. */
  65869. set: function (callback) {
  65870. if (this._onBeforeRenderObserver) {
  65871. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65872. }
  65873. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65874. },
  65875. enumerable: true,
  65876. configurable: true
  65877. });
  65878. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65879. /**
  65880. * A function that is added to the onAfterRenderObservable
  65881. */
  65882. set: function (callback) {
  65883. if (this._onAfterRenderObserver) {
  65884. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65885. }
  65886. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65887. },
  65888. enumerable: true,
  65889. configurable: true
  65890. });
  65891. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65892. /**
  65893. * 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
  65894. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65895. */
  65896. get: function () {
  65897. return this._textures.data[this._currentRenderTextureInd];
  65898. },
  65899. set: function (value) {
  65900. this._forcedOutputTexture = value;
  65901. },
  65902. enumerable: true,
  65903. configurable: true
  65904. });
  65905. /**
  65906. * Gets the camera which post process is applied to.
  65907. * @returns The camera the post process is applied to.
  65908. */
  65909. PostProcess.prototype.getCamera = function () {
  65910. return this._camera;
  65911. };
  65912. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65913. /**
  65914. * Gets the texel size of the postprocess.
  65915. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65916. */
  65917. get: function () {
  65918. if (this._shareOutputWithPostProcess) {
  65919. return this._shareOutputWithPostProcess.texelSize;
  65920. }
  65921. if (this._forcedOutputTexture) {
  65922. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65923. }
  65924. return this._texelSize;
  65925. },
  65926. enumerable: true,
  65927. configurable: true
  65928. });
  65929. /**
  65930. * Gets the engine which this post process belongs to.
  65931. * @returns The engine the post process was enabled with.
  65932. */
  65933. PostProcess.prototype.getEngine = function () {
  65934. return this._engine;
  65935. };
  65936. /**
  65937. * The effect that is created when initializing the post process.
  65938. * @returns The created effect corrisponding the the postprocess.
  65939. */
  65940. PostProcess.prototype.getEffect = function () {
  65941. return this._effect;
  65942. };
  65943. /**
  65944. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65945. * @param postProcess The post process to share the output with.
  65946. * @returns This post process.
  65947. */
  65948. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65949. this._disposeTextures();
  65950. this._shareOutputWithPostProcess = postProcess;
  65951. return this;
  65952. };
  65953. /**
  65954. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65955. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65956. */
  65957. PostProcess.prototype.useOwnOutput = function () {
  65958. if (this._textures.length == 0) {
  65959. this._textures = new BABYLON.SmartArray(2);
  65960. }
  65961. this._shareOutputWithPostProcess = null;
  65962. };
  65963. /**
  65964. * Updates the effect with the current post process compile time values and recompiles the shader.
  65965. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65966. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65967. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65968. * @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
  65969. * @param onCompiled Called when the shader has been compiled.
  65970. * @param onError Called if there is an error when compiling a shader.
  65971. */
  65972. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65973. if (defines === void 0) { defines = null; }
  65974. if (uniforms === void 0) { uniforms = null; }
  65975. if (samplers === void 0) { samplers = null; }
  65976. 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);
  65977. };
  65978. /**
  65979. * The post process is reusable if it can be used multiple times within one frame.
  65980. * @returns If the post process is reusable
  65981. */
  65982. PostProcess.prototype.isReusable = function () {
  65983. return this._reusable;
  65984. };
  65985. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65986. PostProcess.prototype.markTextureDirty = function () {
  65987. this.width = -1;
  65988. };
  65989. /**
  65990. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65991. * 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.
  65992. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65993. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65994. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65995. * @returns The target texture that was bound to be written to.
  65996. */
  65997. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65998. var _this = this;
  65999. if (sourceTexture === void 0) { sourceTexture = null; }
  66000. camera = camera || this._camera;
  66001. var scene = camera.getScene();
  66002. var engine = scene.getEngine();
  66003. var maxSize = engine.getCaps().maxTextureSize;
  66004. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  66005. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  66006. // 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
  66007. var webVRCamera = camera.parent;
  66008. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  66009. requiredWidth /= 2;
  66010. }
  66011. var desiredWidth = (this._options.width || requiredWidth);
  66012. var desiredHeight = this._options.height || requiredHeight;
  66013. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  66014. if (this.adaptScaleToCurrentViewport) {
  66015. var currentViewport = engine.currentViewport;
  66016. if (currentViewport) {
  66017. desiredWidth *= currentViewport.width;
  66018. desiredHeight *= currentViewport.height;
  66019. }
  66020. }
  66021. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  66022. if (!this._options.width) {
  66023. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  66024. }
  66025. if (!this._options.height) {
  66026. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  66027. }
  66028. }
  66029. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  66030. if (this._textures.length > 0) {
  66031. for (var i = 0; i < this._textures.length; i++) {
  66032. this._engine._releaseTexture(this._textures.data[i]);
  66033. }
  66034. this._textures.reset();
  66035. }
  66036. this.width = desiredWidth;
  66037. this.height = desiredHeight;
  66038. var textureSize = { width: this.width, height: this.height };
  66039. var textureOptions = {
  66040. generateMipMaps: false,
  66041. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  66042. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  66043. samplingMode: this.renderTargetSamplingMode,
  66044. type: this._textureType
  66045. };
  66046. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66047. if (this._reusable) {
  66048. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66049. }
  66050. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  66051. this.onSizeChangedObservable.notifyObservers(this);
  66052. }
  66053. this._textures.forEach(function (texture) {
  66054. if (texture.samples !== _this.samples) {
  66055. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  66056. }
  66057. });
  66058. }
  66059. var target;
  66060. if (this._shareOutputWithPostProcess) {
  66061. target = this._shareOutputWithPostProcess.inputTexture;
  66062. }
  66063. else if (this._forcedOutputTexture) {
  66064. target = this._forcedOutputTexture;
  66065. this.width = this._forcedOutputTexture.width;
  66066. this.height = this._forcedOutputTexture.height;
  66067. }
  66068. else {
  66069. target = this.inputTexture;
  66070. }
  66071. // Bind the input of this post process to be used as the output of the previous post process.
  66072. if (this.enablePixelPerfectMode) {
  66073. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  66074. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  66075. }
  66076. else {
  66077. this._scaleRatio.copyFromFloats(1, 1);
  66078. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  66079. }
  66080. this.onActivateObservable.notifyObservers(camera);
  66081. // Clear
  66082. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  66083. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  66084. }
  66085. if (this._reusable) {
  66086. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  66087. }
  66088. return target;
  66089. };
  66090. Object.defineProperty(PostProcess.prototype, "isSupported", {
  66091. /**
  66092. * If the post process is supported.
  66093. */
  66094. get: function () {
  66095. return this._effect.isSupported;
  66096. },
  66097. enumerable: true,
  66098. configurable: true
  66099. });
  66100. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  66101. /**
  66102. * The aspect ratio of the output texture.
  66103. */
  66104. get: function () {
  66105. if (this._shareOutputWithPostProcess) {
  66106. return this._shareOutputWithPostProcess.aspectRatio;
  66107. }
  66108. if (this._forcedOutputTexture) {
  66109. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  66110. }
  66111. return this.width / this.height;
  66112. },
  66113. enumerable: true,
  66114. configurable: true
  66115. });
  66116. /**
  66117. * Get a value indicating if the post-process is ready to be used
  66118. * @returns true if the post-process is ready (shader is compiled)
  66119. */
  66120. PostProcess.prototype.isReady = function () {
  66121. return this._effect && this._effect.isReady();
  66122. };
  66123. /**
  66124. * Binds all textures and uniforms to the shader, this will be run on every pass.
  66125. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  66126. */
  66127. PostProcess.prototype.apply = function () {
  66128. // Check
  66129. if (!this._effect || !this._effect.isReady())
  66130. return null;
  66131. // States
  66132. this._engine.enableEffect(this._effect);
  66133. this._engine.setState(false);
  66134. this._engine.setDepthBuffer(false);
  66135. this._engine.setDepthWrite(false);
  66136. // Alpha
  66137. this._engine.setAlphaMode(this.alphaMode);
  66138. if (this.alphaConstants) {
  66139. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  66140. }
  66141. // Bind the output texture of the preivous post process as the input to this post process.
  66142. var source;
  66143. if (this._shareOutputWithPostProcess) {
  66144. source = this._shareOutputWithPostProcess.inputTexture;
  66145. }
  66146. else if (this._forcedOutputTexture) {
  66147. source = this._forcedOutputTexture;
  66148. }
  66149. else {
  66150. source = this.inputTexture;
  66151. }
  66152. this._effect._bindTexture("textureSampler", source);
  66153. // Parameters
  66154. this._effect.setVector2("scale", this._scaleRatio);
  66155. this.onApplyObservable.notifyObservers(this._effect);
  66156. return this._effect;
  66157. };
  66158. PostProcess.prototype._disposeTextures = function () {
  66159. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66160. return;
  66161. }
  66162. if (this._textures.length > 0) {
  66163. for (var i = 0; i < this._textures.length; i++) {
  66164. this._engine._releaseTexture(this._textures.data[i]);
  66165. }
  66166. }
  66167. this._textures.dispose();
  66168. };
  66169. /**
  66170. * Disposes the post process.
  66171. * @param camera The camera to dispose the post process on.
  66172. */
  66173. PostProcess.prototype.dispose = function (camera) {
  66174. camera = camera || this._camera;
  66175. this._disposeTextures();
  66176. if (this._scene) {
  66177. var index_1 = this._scene.postProcesses.indexOf(this);
  66178. if (index_1 !== -1) {
  66179. this._scene.postProcesses.splice(index_1, 1);
  66180. }
  66181. }
  66182. else {
  66183. var index_2 = this._engine.postProcesses.indexOf(this);
  66184. if (index_2 !== -1) {
  66185. this._engine.postProcesses.splice(index_2, 1);
  66186. }
  66187. }
  66188. if (!camera) {
  66189. return;
  66190. }
  66191. camera.detachPostProcess(this);
  66192. var index = camera._postProcesses.indexOf(this);
  66193. if (index === 0 && camera._postProcesses.length > 0) {
  66194. var firstPostProcess = this._camera._getFirstPostProcess();
  66195. if (firstPostProcess) {
  66196. firstPostProcess.markTextureDirty();
  66197. }
  66198. }
  66199. this.onActivateObservable.clear();
  66200. this.onAfterRenderObservable.clear();
  66201. this.onApplyObservable.clear();
  66202. this.onBeforeRenderObservable.clear();
  66203. this.onSizeChangedObservable.clear();
  66204. };
  66205. return PostProcess;
  66206. }());
  66207. BABYLON.PostProcess = PostProcess;
  66208. })(BABYLON || (BABYLON = {}));
  66209. //# sourceMappingURL=babylon.postProcess.js.map
  66210. var BABYLON;
  66211. (function (BABYLON) {
  66212. var PassPostProcess = /** @class */ (function (_super) {
  66213. __extends(PassPostProcess, _super);
  66214. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66215. if (camera === void 0) { camera = null; }
  66216. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66217. if (blockCompilation === void 0) { blockCompilation = false; }
  66218. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66219. }
  66220. return PassPostProcess;
  66221. }(BABYLON.PostProcess));
  66222. BABYLON.PassPostProcess = PassPostProcess;
  66223. })(BABYLON || (BABYLON = {}));
  66224. //# sourceMappingURL=babylon.passPostProcess.js.map
  66225. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66226. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66227. s = arguments[i];
  66228. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66229. t[p] = s[p];
  66230. }
  66231. return t;
  66232. };
  66233. var BABYLON;
  66234. (function (BABYLON) {
  66235. /**
  66236. * Default implementation IShadowGenerator.
  66237. * This is the main object responsible of generating shadows in the framework.
  66238. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66239. */
  66240. var ShadowGenerator = /** @class */ (function () {
  66241. /**
  66242. * Creates a ShadowGenerator object.
  66243. * A ShadowGenerator is the required tool to use the shadows.
  66244. * Each light casting shadows needs to use its own ShadowGenerator.
  66245. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66246. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66247. * @param light The light object generating the shadows.
  66248. * @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.
  66249. */
  66250. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66251. this._bias = 0.00005;
  66252. this._normalBias = 0;
  66253. this._blurBoxOffset = 1;
  66254. this._blurScale = 2;
  66255. this._blurKernel = 1;
  66256. this._useKernelBlur = false;
  66257. this._filter = ShadowGenerator.FILTER_NONE;
  66258. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66259. this._contactHardeningLightSizeUVRatio = 0.1;
  66260. this._darkness = 0;
  66261. this._transparencyShadow = false;
  66262. /**
  66263. * Controls the extent to which the shadows fade out at the edge of the frustum
  66264. * Used only by directionals and spots
  66265. */
  66266. this.frustumEdgeFalloff = 0;
  66267. /**
  66268. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66269. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66270. * It might on the other hand introduce peter panning.
  66271. */
  66272. this.forceBackFacesOnly = false;
  66273. this._lightDirection = BABYLON.Vector3.Zero();
  66274. this._viewMatrix = BABYLON.Matrix.Zero();
  66275. this._projectionMatrix = BABYLON.Matrix.Zero();
  66276. this._transformMatrix = BABYLON.Matrix.Zero();
  66277. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66278. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66279. this._currentFaceIndex = 0;
  66280. this._currentFaceIndexCache = 0;
  66281. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66282. this._mapSize = mapSize;
  66283. this._light = light;
  66284. this._scene = light.getScene();
  66285. light._shadowGenerator = this;
  66286. // Texture type fallback from float to int if not supported.
  66287. var caps = this._scene.getEngine().getCaps();
  66288. if (!useFullFloatFirst) {
  66289. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66290. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66291. }
  66292. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66293. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66294. }
  66295. else {
  66296. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66297. }
  66298. }
  66299. else {
  66300. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66301. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66302. }
  66303. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66304. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66305. }
  66306. else {
  66307. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66308. }
  66309. }
  66310. this._initializeGenerator();
  66311. this._applyFilterValues();
  66312. }
  66313. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66314. /**
  66315. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66316. */
  66317. get: function () {
  66318. return this._bias;
  66319. },
  66320. /**
  66321. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66322. */
  66323. set: function (bias) {
  66324. this._bias = bias;
  66325. },
  66326. enumerable: true,
  66327. configurable: true
  66328. });
  66329. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66330. /**
  66331. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66332. */
  66333. get: function () {
  66334. return this._normalBias;
  66335. },
  66336. /**
  66337. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66338. */
  66339. set: function (normalBias) {
  66340. this._normalBias = normalBias;
  66341. },
  66342. enumerable: true,
  66343. configurable: true
  66344. });
  66345. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66346. /**
  66347. * Gets the blur box offset: offset applied during the blur pass.
  66348. * Only usefull if useKernelBlur = false
  66349. */
  66350. get: function () {
  66351. return this._blurBoxOffset;
  66352. },
  66353. /**
  66354. * Sets the blur box offset: offset applied during the blur pass.
  66355. * Only usefull if useKernelBlur = false
  66356. */
  66357. set: function (value) {
  66358. if (this._blurBoxOffset === value) {
  66359. return;
  66360. }
  66361. this._blurBoxOffset = value;
  66362. this._disposeBlurPostProcesses();
  66363. },
  66364. enumerable: true,
  66365. configurable: true
  66366. });
  66367. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66368. /**
  66369. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66370. * 2 means half of the size.
  66371. */
  66372. get: function () {
  66373. return this._blurScale;
  66374. },
  66375. /**
  66376. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66377. * 2 means half of the size.
  66378. */
  66379. set: function (value) {
  66380. if (this._blurScale === value) {
  66381. return;
  66382. }
  66383. this._blurScale = value;
  66384. this._disposeBlurPostProcesses();
  66385. },
  66386. enumerable: true,
  66387. configurable: true
  66388. });
  66389. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66390. /**
  66391. * Gets the blur kernel: kernel size of the blur pass.
  66392. * Only usefull if useKernelBlur = true
  66393. */
  66394. get: function () {
  66395. return this._blurKernel;
  66396. },
  66397. /**
  66398. * Sets the blur kernel: kernel size of the blur pass.
  66399. * Only usefull if useKernelBlur = true
  66400. */
  66401. set: function (value) {
  66402. if (this._blurKernel === value) {
  66403. return;
  66404. }
  66405. this._blurKernel = value;
  66406. this._disposeBlurPostProcesses();
  66407. },
  66408. enumerable: true,
  66409. configurable: true
  66410. });
  66411. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66412. /**
  66413. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66414. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66415. */
  66416. get: function () {
  66417. return this._useKernelBlur;
  66418. },
  66419. /**
  66420. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66421. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66422. */
  66423. set: function (value) {
  66424. if (this._useKernelBlur === value) {
  66425. return;
  66426. }
  66427. this._useKernelBlur = value;
  66428. this._disposeBlurPostProcesses();
  66429. },
  66430. enumerable: true,
  66431. configurable: true
  66432. });
  66433. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66434. /**
  66435. * Gets the depth scale used in ESM mode.
  66436. */
  66437. get: function () {
  66438. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66439. },
  66440. /**
  66441. * Sets the depth scale used in ESM mode.
  66442. * This can override the scale stored on the light.
  66443. */
  66444. set: function (value) {
  66445. this._depthScale = value;
  66446. },
  66447. enumerable: true,
  66448. configurable: true
  66449. });
  66450. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66451. /**
  66452. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66453. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66454. */
  66455. get: function () {
  66456. return this._filter;
  66457. },
  66458. /**
  66459. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66460. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66461. */
  66462. set: function (value) {
  66463. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66464. if (this._light.needCube()) {
  66465. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66466. this.useExponentialShadowMap = true;
  66467. return;
  66468. }
  66469. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66470. this.useCloseExponentialShadowMap = true;
  66471. return;
  66472. }
  66473. // PCF on cubemap would also be expensive
  66474. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66475. this.usePoissonSampling = true;
  66476. return;
  66477. }
  66478. }
  66479. // Weblg1 fallback for PCF.
  66480. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66481. if (this._scene.getEngine().webGLVersion === 1) {
  66482. this.usePoissonSampling = true;
  66483. return;
  66484. }
  66485. }
  66486. if (this._filter === value) {
  66487. return;
  66488. }
  66489. this._filter = value;
  66490. this._disposeBlurPostProcesses();
  66491. this._applyFilterValues();
  66492. this._light._markMeshesAsLightDirty();
  66493. },
  66494. enumerable: true,
  66495. configurable: true
  66496. });
  66497. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66498. /**
  66499. * Gets if the current filter is set to Poisson Sampling.
  66500. */
  66501. get: function () {
  66502. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66503. },
  66504. /**
  66505. * Sets the current filter to Poisson Sampling.
  66506. */
  66507. set: function (value) {
  66508. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66509. return;
  66510. }
  66511. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66512. },
  66513. enumerable: true,
  66514. configurable: true
  66515. });
  66516. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66517. /**
  66518. * Gets if the current filter is set to VSM.
  66519. * DEPRECATED. Should use useExponentialShadowMap instead.
  66520. */
  66521. get: function () {
  66522. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66523. return this.useExponentialShadowMap;
  66524. },
  66525. /**
  66526. * Sets the current filter is to VSM.
  66527. * DEPRECATED. Should use useExponentialShadowMap instead.
  66528. */
  66529. set: function (value) {
  66530. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66531. this.useExponentialShadowMap = value;
  66532. },
  66533. enumerable: true,
  66534. configurable: true
  66535. });
  66536. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66537. /**
  66538. * Gets if the current filter is set to blurred VSM.
  66539. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66540. */
  66541. get: function () {
  66542. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66543. return this.useBlurExponentialShadowMap;
  66544. },
  66545. /**
  66546. * Sets the current filter is to blurred VSM.
  66547. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66548. */
  66549. set: function (value) {
  66550. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66551. this.useBlurExponentialShadowMap = value;
  66552. },
  66553. enumerable: true,
  66554. configurable: true
  66555. });
  66556. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66557. /**
  66558. * Gets if the current filter is set to ESM.
  66559. */
  66560. get: function () {
  66561. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66562. },
  66563. /**
  66564. * Sets the current filter is to ESM.
  66565. */
  66566. set: function (value) {
  66567. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66568. return;
  66569. }
  66570. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66571. },
  66572. enumerable: true,
  66573. configurable: true
  66574. });
  66575. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66576. /**
  66577. * Gets if the current filter is set to filtered ESM.
  66578. */
  66579. get: function () {
  66580. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66581. },
  66582. /**
  66583. * Gets if the current filter is set to filtered ESM.
  66584. */
  66585. set: function (value) {
  66586. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66587. return;
  66588. }
  66589. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66590. },
  66591. enumerable: true,
  66592. configurable: true
  66593. });
  66594. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66595. /**
  66596. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66597. * exponential to prevent steep falloff artifacts).
  66598. */
  66599. get: function () {
  66600. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66601. },
  66602. /**
  66603. * Sets the current filter to "close ESM" (using the inverse of the
  66604. * exponential to prevent steep falloff artifacts).
  66605. */
  66606. set: function (value) {
  66607. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66608. return;
  66609. }
  66610. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66611. },
  66612. enumerable: true,
  66613. configurable: true
  66614. });
  66615. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66616. /**
  66617. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66618. * exponential to prevent steep falloff artifacts).
  66619. */
  66620. get: function () {
  66621. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66622. },
  66623. /**
  66624. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66625. * exponential to prevent steep falloff artifacts).
  66626. */
  66627. set: function (value) {
  66628. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66629. return;
  66630. }
  66631. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66632. },
  66633. enumerable: true,
  66634. configurable: true
  66635. });
  66636. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66637. /**
  66638. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66639. */
  66640. get: function () {
  66641. return this.filter === ShadowGenerator.FILTER_PCF;
  66642. },
  66643. /**
  66644. * Sets the current filter to "PCF" (percentage closer filtering).
  66645. */
  66646. set: function (value) {
  66647. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66648. return;
  66649. }
  66650. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66651. },
  66652. enumerable: true,
  66653. configurable: true
  66654. });
  66655. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66656. /**
  66657. * Gets the PCF or PCSS Quality.
  66658. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66659. */
  66660. get: function () {
  66661. return this._filteringQuality;
  66662. },
  66663. /**
  66664. * Sets the PCF or PCSS Quality.
  66665. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66666. */
  66667. set: function (filteringQuality) {
  66668. this._filteringQuality = filteringQuality;
  66669. },
  66670. enumerable: true,
  66671. configurable: true
  66672. });
  66673. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66674. /**
  66675. * Gets if the current filter is set to "PCSS" (contact hardening).
  66676. */
  66677. get: function () {
  66678. return this.filter === ShadowGenerator.FILTER_PCSS;
  66679. },
  66680. /**
  66681. * Sets the current filter to "PCSS" (contact hardening).
  66682. */
  66683. set: function (value) {
  66684. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66685. return;
  66686. }
  66687. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66688. },
  66689. enumerable: true,
  66690. configurable: true
  66691. });
  66692. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66693. /**
  66694. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66695. * Using a ratio helps keeping shape stability independently of the map size.
  66696. *
  66697. * It does not account for the light projection as it was having too much
  66698. * instability during the light setup or during light position changes.
  66699. *
  66700. * Only valid if useContactHardeningShadow is true.
  66701. */
  66702. get: function () {
  66703. return this._contactHardeningLightSizeUVRatio;
  66704. },
  66705. /**
  66706. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66707. * Using a ratio helps keeping shape stability independently of the map size.
  66708. *
  66709. * It does not account for the light projection as it was having too much
  66710. * instability during the light setup or during light position changes.
  66711. *
  66712. * Only valid if useContactHardeningShadow is true.
  66713. */
  66714. set: function (contactHardeningLightSizeUVRatio) {
  66715. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66716. },
  66717. enumerable: true,
  66718. configurable: true
  66719. });
  66720. /**
  66721. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66722. * 0 means strongest and 1 would means no shadow.
  66723. * @returns the darkness.
  66724. */
  66725. ShadowGenerator.prototype.getDarkness = function () {
  66726. return this._darkness;
  66727. };
  66728. /**
  66729. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66730. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66731. * @returns the shadow generator allowing fluent coding.
  66732. */
  66733. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66734. if (darkness >= 1.0)
  66735. this._darkness = 1.0;
  66736. else if (darkness <= 0.0)
  66737. this._darkness = 0.0;
  66738. else
  66739. this._darkness = darkness;
  66740. return this;
  66741. };
  66742. /**
  66743. * Sets the ability to have transparent shadow (boolean).
  66744. * @param transparent True if transparent else False
  66745. * @returns the shadow generator allowing fluent coding
  66746. */
  66747. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66748. this._transparencyShadow = transparent;
  66749. return this;
  66750. };
  66751. /**
  66752. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66753. * @returns The render target texture if present otherwise, null
  66754. */
  66755. ShadowGenerator.prototype.getShadowMap = function () {
  66756. return this._shadowMap;
  66757. };
  66758. /**
  66759. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66760. * @returns The render target texture if the shadow map is present otherwise, null
  66761. */
  66762. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66763. if (this._shadowMap2) {
  66764. return this._shadowMap2;
  66765. }
  66766. return this._shadowMap;
  66767. };
  66768. /**
  66769. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66770. * @param mesh Mesh to add
  66771. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66772. * @returns the Shadow Generator itself
  66773. */
  66774. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66775. if (includeDescendants === void 0) { includeDescendants = true; }
  66776. if (!this._shadowMap) {
  66777. return this;
  66778. }
  66779. if (!this._shadowMap.renderList) {
  66780. this._shadowMap.renderList = [];
  66781. }
  66782. this._shadowMap.renderList.push(mesh);
  66783. if (includeDescendants) {
  66784. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66785. }
  66786. return this;
  66787. var _a;
  66788. };
  66789. /**
  66790. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66791. * @param mesh Mesh to remove
  66792. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66793. * @returns the Shadow Generator itself
  66794. */
  66795. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66796. if (includeDescendants === void 0) { includeDescendants = true; }
  66797. if (!this._shadowMap || !this._shadowMap.renderList) {
  66798. return this;
  66799. }
  66800. var index = this._shadowMap.renderList.indexOf(mesh);
  66801. if (index !== -1) {
  66802. this._shadowMap.renderList.splice(index, 1);
  66803. }
  66804. if (includeDescendants) {
  66805. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66806. var child = _a[_i];
  66807. this.removeShadowCaster(child);
  66808. }
  66809. }
  66810. return this;
  66811. };
  66812. /**
  66813. * Returns the associated light object.
  66814. * @returns the light generating the shadow
  66815. */
  66816. ShadowGenerator.prototype.getLight = function () {
  66817. return this._light;
  66818. };
  66819. ShadowGenerator.prototype._initializeGenerator = function () {
  66820. this._light._markMeshesAsLightDirty();
  66821. this._initializeShadowMap();
  66822. };
  66823. ShadowGenerator.prototype._initializeShadowMap = function () {
  66824. var _this = this;
  66825. // Render target
  66826. var engine = this._scene.getEngine();
  66827. if (engine.webGLVersion > 1) {
  66828. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66829. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66830. }
  66831. else {
  66832. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66833. }
  66834. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66835. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66836. this._shadowMap.anisotropicFilteringLevel = 1;
  66837. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66838. this._shadowMap.renderParticles = false;
  66839. this._shadowMap.ignoreCameraViewport = true;
  66840. // Record Face Index before render.
  66841. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66842. _this._currentFaceIndex = faceIndex;
  66843. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66844. engine.setColorWrite(false);
  66845. }
  66846. });
  66847. // Custom render function.
  66848. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66849. // Blur if required afer render.
  66850. this._shadowMap.onAfterUnbindObservable.add(function () {
  66851. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66852. engine.setColorWrite(true);
  66853. }
  66854. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66855. return;
  66856. }
  66857. var shadowMap = _this.getShadowMapForRendering();
  66858. if (shadowMap) {
  66859. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66860. }
  66861. });
  66862. // Clear according to the chosen filter.
  66863. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66864. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66865. this._shadowMap.onClearObservable.add(function (engine) {
  66866. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66867. engine.clear(clearOne, false, true, false);
  66868. }
  66869. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66870. engine.clear(clearZero, true, true, false);
  66871. }
  66872. else {
  66873. engine.clear(clearOne, true, true, false);
  66874. }
  66875. });
  66876. };
  66877. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66878. var _this = this;
  66879. var engine = this._scene.getEngine();
  66880. var targetSize = this._mapSize / this.blurScale;
  66881. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66882. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66883. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66884. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66885. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66886. }
  66887. if (this.useKernelBlur) {
  66888. 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);
  66889. this._kernelBlurXPostprocess.width = targetSize;
  66890. this._kernelBlurXPostprocess.height = targetSize;
  66891. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66892. effect.setTexture("textureSampler", _this._shadowMap);
  66893. });
  66894. 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);
  66895. this._kernelBlurXPostprocess.autoClear = false;
  66896. this._kernelBlurYPostprocess.autoClear = false;
  66897. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66898. this._kernelBlurXPostprocess.packedFloat = true;
  66899. this._kernelBlurYPostprocess.packedFloat = true;
  66900. }
  66901. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66902. }
  66903. else {
  66904. 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);
  66905. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66906. effect.setFloat2("screenSize", targetSize, targetSize);
  66907. effect.setTexture("textureSampler", _this._shadowMap);
  66908. });
  66909. this._boxBlurPostprocess.autoClear = false;
  66910. this._blurPostProcesses = [this._boxBlurPostprocess];
  66911. }
  66912. };
  66913. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66914. var index;
  66915. var engine = this._scene.getEngine();
  66916. if (depthOnlySubMeshes.length) {
  66917. engine.setColorWrite(false);
  66918. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66919. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66920. }
  66921. engine.setColorWrite(true);
  66922. }
  66923. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66924. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66925. }
  66926. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66927. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66928. }
  66929. if (this._transparencyShadow) {
  66930. for (index = 0; index < transparentSubMeshes.length; index++) {
  66931. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66932. }
  66933. }
  66934. };
  66935. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66936. var _this = this;
  66937. var mesh = subMesh.getRenderingMesh();
  66938. var scene = this._scene;
  66939. var engine = scene.getEngine();
  66940. var material = subMesh.getMaterial();
  66941. if (!material) {
  66942. return;
  66943. }
  66944. // Culling
  66945. engine.setState(material.backFaceCulling);
  66946. // Managing instances
  66947. var batch = mesh._getInstancesRenderList(subMesh._id);
  66948. if (batch.mustReturn) {
  66949. return;
  66950. }
  66951. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66952. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66953. engine.enableEffect(this._effect);
  66954. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66955. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66956. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66957. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66958. this._effect.setVector3("lightData", this._cachedDirection);
  66959. }
  66960. else {
  66961. this._effect.setVector3("lightData", this._cachedPosition);
  66962. }
  66963. if (scene.activeCamera) {
  66964. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66965. }
  66966. // Alpha test
  66967. if (material && material.needAlphaTesting()) {
  66968. var alphaTexture = material.getAlphaTestTexture();
  66969. if (alphaTexture) {
  66970. this._effect.setTexture("diffuseSampler", alphaTexture);
  66971. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66972. }
  66973. }
  66974. // Bones
  66975. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66976. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66977. }
  66978. // Morph targets
  66979. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66980. if (this.forceBackFacesOnly) {
  66981. engine.setState(true, 0, false, true);
  66982. }
  66983. // Draw
  66984. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66985. if (this.forceBackFacesOnly) {
  66986. engine.setState(true, 0, false, false);
  66987. }
  66988. }
  66989. else {
  66990. // Need to reset refresh rate of the shadowMap
  66991. if (this._shadowMap) {
  66992. this._shadowMap.resetRefreshCounter();
  66993. }
  66994. }
  66995. };
  66996. ShadowGenerator.prototype._applyFilterValues = function () {
  66997. if (!this._shadowMap) {
  66998. return;
  66999. }
  67000. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  67001. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67002. }
  67003. else {
  67004. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67005. }
  67006. };
  67007. /**
  67008. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67009. * @param onCompiled Callback triggered at the and of the effects compilation
  67010. * @param options Sets of optional options forcing the compilation with different modes
  67011. */
  67012. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  67013. var _this = this;
  67014. var localOptions = __assign({ useInstances: false }, options);
  67015. var shadowMap = this.getShadowMap();
  67016. if (!shadowMap) {
  67017. if (onCompiled) {
  67018. onCompiled(this);
  67019. }
  67020. return;
  67021. }
  67022. var renderList = shadowMap.renderList;
  67023. if (!renderList) {
  67024. if (onCompiled) {
  67025. onCompiled(this);
  67026. }
  67027. return;
  67028. }
  67029. var subMeshes = new Array();
  67030. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  67031. var mesh = renderList_1[_i];
  67032. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  67033. }
  67034. if (subMeshes.length === 0) {
  67035. if (onCompiled) {
  67036. onCompiled(this);
  67037. }
  67038. return;
  67039. }
  67040. var currentIndex = 0;
  67041. var checkReady = function () {
  67042. if (!_this._scene || !_this._scene.getEngine()) {
  67043. return;
  67044. }
  67045. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  67046. currentIndex++;
  67047. if (currentIndex >= subMeshes.length) {
  67048. if (onCompiled) {
  67049. onCompiled(_this);
  67050. }
  67051. return;
  67052. }
  67053. }
  67054. setTimeout(checkReady, 16);
  67055. };
  67056. checkReady();
  67057. };
  67058. /**
  67059. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67060. * @param options Sets of optional options forcing the compilation with different modes
  67061. * @returns A promise that resolves when the compilation completes
  67062. */
  67063. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  67064. var _this = this;
  67065. return new Promise(function (resolve) {
  67066. _this.forceCompilation(function () {
  67067. resolve();
  67068. }, options);
  67069. });
  67070. };
  67071. /**
  67072. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  67073. * @param subMesh The submesh we want to render in the shadow map
  67074. * @param useInstances Defines wether will draw in the map using instances
  67075. * @returns true if ready otherwise, false
  67076. */
  67077. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  67078. var defines = [];
  67079. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67080. defines.push("#define FLOAT");
  67081. }
  67082. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67083. defines.push("#define ESM");
  67084. }
  67085. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  67086. defines.push("#define DEPTHTEXTURE");
  67087. }
  67088. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67089. var mesh = subMesh.getMesh();
  67090. var material = subMesh.getMaterial();
  67091. // Normal bias.
  67092. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  67093. attribs.push(BABYLON.VertexBuffer.NormalKind);
  67094. defines.push("#define NORMAL");
  67095. if (mesh.nonUniformScaling) {
  67096. defines.push("#define NONUNIFORMSCALING");
  67097. }
  67098. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67099. defines.push("#define DIRECTIONINLIGHTDATA");
  67100. }
  67101. }
  67102. // Alpha test
  67103. if (material && material.needAlphaTesting()) {
  67104. var alphaTexture = material.getAlphaTestTexture();
  67105. if (alphaTexture) {
  67106. defines.push("#define ALPHATEST");
  67107. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67108. attribs.push(BABYLON.VertexBuffer.UVKind);
  67109. defines.push("#define UV1");
  67110. }
  67111. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67112. if (alphaTexture.coordinatesIndex === 1) {
  67113. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67114. defines.push("#define UV2");
  67115. }
  67116. }
  67117. }
  67118. }
  67119. // Bones
  67120. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67121. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67122. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67123. if (mesh.numBoneInfluencers > 4) {
  67124. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67125. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67126. }
  67127. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67128. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67129. }
  67130. else {
  67131. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67132. }
  67133. // Morph targets
  67134. var manager = mesh.morphTargetManager;
  67135. var morphInfluencers = 0;
  67136. if (manager) {
  67137. if (manager.numInfluencers > 0) {
  67138. defines.push("#define MORPHTARGETS");
  67139. morphInfluencers = manager.numInfluencers;
  67140. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  67141. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  67142. }
  67143. }
  67144. // Instances
  67145. if (useInstances) {
  67146. defines.push("#define INSTANCES");
  67147. attribs.push("world0");
  67148. attribs.push("world1");
  67149. attribs.push("world2");
  67150. attribs.push("world3");
  67151. }
  67152. // Get correct effect
  67153. var join = defines.join("\n");
  67154. if (this._cachedDefines !== join) {
  67155. this._cachedDefines = join;
  67156. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  67157. }
  67158. if (!this._effect.isReady()) {
  67159. return false;
  67160. }
  67161. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67162. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67163. this._initializeBlurRTTAndPostProcesses();
  67164. }
  67165. }
  67166. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67167. return false;
  67168. }
  67169. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67170. return false;
  67171. }
  67172. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67173. return false;
  67174. }
  67175. return true;
  67176. };
  67177. /**
  67178. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67179. * @param defines Defines of the material we want to update
  67180. * @param lightIndex Index of the light in the enabled light list of the material
  67181. */
  67182. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67183. var scene = this._scene;
  67184. var light = this._light;
  67185. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67186. return;
  67187. }
  67188. defines["SHADOW" + lightIndex] = true;
  67189. if (this.useContactHardeningShadow) {
  67190. defines["SHADOWPCSS" + lightIndex] = true;
  67191. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67192. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67193. }
  67194. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67195. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67196. }
  67197. // else default to high.
  67198. }
  67199. if (this.usePercentageCloserFiltering) {
  67200. defines["SHADOWPCF" + lightIndex] = true;
  67201. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67202. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67203. }
  67204. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67205. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67206. }
  67207. // else default to high.
  67208. }
  67209. else if (this.usePoissonSampling) {
  67210. defines["SHADOWPOISSON" + lightIndex] = true;
  67211. }
  67212. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67213. defines["SHADOWESM" + lightIndex] = true;
  67214. }
  67215. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67216. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67217. }
  67218. if (light.needCube()) {
  67219. defines["SHADOWCUBE" + lightIndex] = true;
  67220. }
  67221. };
  67222. /**
  67223. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67224. * defined in the generator but impacting the effect).
  67225. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67226. * @param effect The effect we are binfing the information for
  67227. */
  67228. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67229. var light = this._light;
  67230. var scene = this._scene;
  67231. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67232. return;
  67233. }
  67234. var camera = scene.activeCamera;
  67235. if (!camera) {
  67236. return;
  67237. }
  67238. var shadowMap = this.getShadowMap();
  67239. if (!shadowMap) {
  67240. return;
  67241. }
  67242. if (!light.needCube()) {
  67243. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67244. }
  67245. // Only PCF uses depth stencil texture.
  67246. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67247. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67248. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67249. }
  67250. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67251. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67252. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67253. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67254. }
  67255. else {
  67256. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67257. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67258. }
  67259. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67260. };
  67261. /**
  67262. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67263. * (eq to shadow prjection matrix * light transform matrix)
  67264. * @returns The transform matrix used to create the shadow map
  67265. */
  67266. ShadowGenerator.prototype.getTransformMatrix = function () {
  67267. var scene = this._scene;
  67268. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67269. return this._transformMatrix;
  67270. }
  67271. this._currentRenderID = scene.getRenderId();
  67272. this._currentFaceIndexCache = this._currentFaceIndex;
  67273. var lightPosition = this._light.position;
  67274. if (this._light.computeTransformedInformation()) {
  67275. lightPosition = this._light.transformedPosition;
  67276. }
  67277. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67278. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67279. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67280. }
  67281. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67282. this._cachedPosition.copyFrom(lightPosition);
  67283. this._cachedDirection.copyFrom(this._lightDirection);
  67284. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67285. var shadowMap = this.getShadowMap();
  67286. if (shadowMap) {
  67287. var renderList = shadowMap.renderList;
  67288. if (renderList) {
  67289. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67290. }
  67291. }
  67292. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67293. }
  67294. return this._transformMatrix;
  67295. };
  67296. /**
  67297. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67298. * Cube and 2D textures for instance.
  67299. */
  67300. ShadowGenerator.prototype.recreateShadowMap = function () {
  67301. var shadowMap = this._shadowMap;
  67302. if (!shadowMap) {
  67303. return;
  67304. }
  67305. // Track render list.
  67306. var renderList = shadowMap.renderList;
  67307. // Clean up existing data.
  67308. this._disposeRTTandPostProcesses();
  67309. // Reinitializes.
  67310. this._initializeGenerator();
  67311. // Reaffect the filter to ensure a correct fallback if necessary.
  67312. this.filter = this.filter;
  67313. // Reaffect the filter.
  67314. this._applyFilterValues();
  67315. // Reaffect Render List.
  67316. this._shadowMap.renderList = renderList;
  67317. };
  67318. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67319. if (this._shadowMap2) {
  67320. this._shadowMap2.dispose();
  67321. this._shadowMap2 = null;
  67322. }
  67323. if (this._boxBlurPostprocess) {
  67324. this._boxBlurPostprocess.dispose();
  67325. this._boxBlurPostprocess = null;
  67326. }
  67327. if (this._kernelBlurXPostprocess) {
  67328. this._kernelBlurXPostprocess.dispose();
  67329. this._kernelBlurXPostprocess = null;
  67330. }
  67331. if (this._kernelBlurYPostprocess) {
  67332. this._kernelBlurYPostprocess.dispose();
  67333. this._kernelBlurYPostprocess = null;
  67334. }
  67335. this._blurPostProcesses = [];
  67336. };
  67337. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67338. if (this._shadowMap) {
  67339. this._shadowMap.dispose();
  67340. this._shadowMap = null;
  67341. }
  67342. this._disposeBlurPostProcesses();
  67343. };
  67344. /**
  67345. * Disposes the ShadowGenerator.
  67346. * Returns nothing.
  67347. */
  67348. ShadowGenerator.prototype.dispose = function () {
  67349. this._disposeRTTandPostProcesses();
  67350. if (this._light) {
  67351. this._light._shadowGenerator = null;
  67352. this._light._markMeshesAsLightDirty();
  67353. }
  67354. };
  67355. /**
  67356. * Serializes the shadow generator setup to a json object.
  67357. * @returns The serialized JSON object
  67358. */
  67359. ShadowGenerator.prototype.serialize = function () {
  67360. var serializationObject = {};
  67361. var shadowMap = this.getShadowMap();
  67362. if (!shadowMap) {
  67363. return serializationObject;
  67364. }
  67365. serializationObject.lightId = this._light.id;
  67366. serializationObject.mapSize = shadowMap.getRenderSize();
  67367. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67368. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67369. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67370. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67371. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67372. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67373. serializationObject.depthScale = this.depthScale;
  67374. serializationObject.darkness = this.getDarkness();
  67375. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67376. serializationObject.blurKernel = this.blurKernel;
  67377. serializationObject.blurScale = this.blurScale;
  67378. serializationObject.useKernelBlur = this.useKernelBlur;
  67379. serializationObject.transparencyShadow = this._transparencyShadow;
  67380. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67381. serializationObject.bias = this.bias;
  67382. serializationObject.normalBias = this.normalBias;
  67383. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67384. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67385. serializationObject.filteringQuality = this.filteringQuality;
  67386. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67387. serializationObject.renderList = [];
  67388. if (shadowMap.renderList) {
  67389. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67390. var mesh = shadowMap.renderList[meshIndex];
  67391. serializationObject.renderList.push(mesh.id);
  67392. }
  67393. }
  67394. return serializationObject;
  67395. };
  67396. /**
  67397. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67398. * @param parsedShadowGenerator The JSON object to parse
  67399. * @param scene The scene to create the shadow map for
  67400. * @returns The parsed shadow generator
  67401. */
  67402. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67403. //casting to point light, as light is missing the position attr and typescript complains.
  67404. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67405. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67406. var shadowMap = shadowGenerator.getShadowMap();
  67407. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67408. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67409. meshes.forEach(function (mesh) {
  67410. if (!shadowMap) {
  67411. return;
  67412. }
  67413. if (!shadowMap.renderList) {
  67414. shadowMap.renderList = [];
  67415. }
  67416. shadowMap.renderList.push(mesh);
  67417. });
  67418. }
  67419. if (parsedShadowGenerator.usePoissonSampling) {
  67420. shadowGenerator.usePoissonSampling = true;
  67421. }
  67422. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67423. shadowGenerator.useExponentialShadowMap = true;
  67424. }
  67425. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67426. shadowGenerator.useBlurExponentialShadowMap = true;
  67427. }
  67428. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67429. shadowGenerator.useCloseExponentialShadowMap = true;
  67430. }
  67431. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67432. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67433. }
  67434. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67435. shadowGenerator.usePercentageCloserFiltering = true;
  67436. }
  67437. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67438. shadowGenerator.useContactHardeningShadow = true;
  67439. }
  67440. if (parsedShadowGenerator.filteringQuality) {
  67441. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67442. }
  67443. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67444. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67445. }
  67446. // Backward compat
  67447. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67448. shadowGenerator.useExponentialShadowMap = true;
  67449. }
  67450. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67451. shadowGenerator.useBlurExponentialShadowMap = true;
  67452. }
  67453. if (parsedShadowGenerator.depthScale) {
  67454. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67455. }
  67456. if (parsedShadowGenerator.blurScale) {
  67457. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67458. }
  67459. if (parsedShadowGenerator.blurBoxOffset) {
  67460. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67461. }
  67462. if (parsedShadowGenerator.useKernelBlur) {
  67463. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67464. }
  67465. if (parsedShadowGenerator.blurKernel) {
  67466. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67467. }
  67468. if (parsedShadowGenerator.bias !== undefined) {
  67469. shadowGenerator.bias = parsedShadowGenerator.bias;
  67470. }
  67471. if (parsedShadowGenerator.normalBias !== undefined) {
  67472. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67473. }
  67474. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67475. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67476. }
  67477. if (parsedShadowGenerator.darkness) {
  67478. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67479. }
  67480. if (parsedShadowGenerator.transparencyShadow) {
  67481. shadowGenerator.setTransparencyShadow(true);
  67482. }
  67483. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67484. return shadowGenerator;
  67485. };
  67486. /**
  67487. * Shadow generator mode None: no filtering applied.
  67488. */
  67489. ShadowGenerator.FILTER_NONE = 0;
  67490. /**
  67491. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67492. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67493. */
  67494. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67495. /**
  67496. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67497. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67498. */
  67499. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67500. /**
  67501. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67502. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67503. */
  67504. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67505. /**
  67506. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67507. * edge artifacts on steep falloff.
  67508. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67509. */
  67510. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67511. /**
  67512. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67513. * edge artifacts on steep falloff.
  67514. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67515. */
  67516. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67517. /**
  67518. * Shadow generator mode PCF: Percentage Closer Filtering
  67519. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67520. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67521. */
  67522. ShadowGenerator.FILTER_PCF = 6;
  67523. /**
  67524. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67525. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67526. * Contact Hardening
  67527. */
  67528. ShadowGenerator.FILTER_PCSS = 7;
  67529. /**
  67530. * Reserved for PCF and PCSS
  67531. * Highest Quality.
  67532. *
  67533. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67534. *
  67535. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67536. */
  67537. ShadowGenerator.QUALITY_HIGH = 0;
  67538. /**
  67539. * Reserved for PCF and PCSS
  67540. * Good tradeoff for quality/perf cross devices
  67541. *
  67542. * Execute PCF on a 3*3 kernel.
  67543. *
  67544. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67545. */
  67546. ShadowGenerator.QUALITY_MEDIUM = 1;
  67547. /**
  67548. * Reserved for PCF and PCSS
  67549. * The lowest quality but the fastest.
  67550. *
  67551. * Execute PCF on a 1*1 kernel.
  67552. *
  67553. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67554. */
  67555. ShadowGenerator.QUALITY_LOW = 2;
  67556. return ShadowGenerator;
  67557. }());
  67558. BABYLON.ShadowGenerator = ShadowGenerator;
  67559. })(BABYLON || (BABYLON = {}));
  67560. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67561. var BABYLON;
  67562. (function (BABYLON) {
  67563. var DefaultLoadingScreen = /** @class */ (function () {
  67564. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67565. if (_loadingText === void 0) { _loadingText = ""; }
  67566. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67567. var _this = this;
  67568. this._renderingCanvas = _renderingCanvas;
  67569. this._loadingText = _loadingText;
  67570. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67571. // Resize
  67572. this._resizeLoadingUI = function () {
  67573. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67574. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67575. if (!_this._loadingDiv) {
  67576. return;
  67577. }
  67578. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67579. _this._loadingDiv.style.left = canvasRect.left + "px";
  67580. _this._loadingDiv.style.top = canvasRect.top + "px";
  67581. _this._loadingDiv.style.width = canvasRect.width + "px";
  67582. _this._loadingDiv.style.height = canvasRect.height + "px";
  67583. };
  67584. }
  67585. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67586. if (this._loadingDiv) {
  67587. // Do not add a loading screen if there is already one
  67588. return;
  67589. }
  67590. this._loadingDiv = document.createElement("div");
  67591. this._loadingDiv.id = "babylonjsLoadingDiv";
  67592. this._loadingDiv.style.opacity = "0";
  67593. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67594. this._loadingDiv.style.pointerEvents = "none";
  67595. // Loading text
  67596. this._loadingTextDiv = document.createElement("div");
  67597. this._loadingTextDiv.style.position = "absolute";
  67598. this._loadingTextDiv.style.left = "0";
  67599. this._loadingTextDiv.style.top = "50%";
  67600. this._loadingTextDiv.style.marginTop = "80px";
  67601. this._loadingTextDiv.style.width = "100%";
  67602. this._loadingTextDiv.style.height = "20px";
  67603. this._loadingTextDiv.style.fontFamily = "Arial";
  67604. this._loadingTextDiv.style.fontSize = "14px";
  67605. this._loadingTextDiv.style.color = "white";
  67606. this._loadingTextDiv.style.textAlign = "center";
  67607. this._loadingTextDiv.innerHTML = "Loading";
  67608. this._loadingDiv.appendChild(this._loadingTextDiv);
  67609. //set the predefined text
  67610. this._loadingTextDiv.innerHTML = this._loadingText;
  67611. // Generating keyframes
  67612. var style = document.createElement('style');
  67613. style.type = 'text/css';
  67614. 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 }";
  67615. style.innerHTML = keyFrames;
  67616. document.getElementsByTagName('head')[0].appendChild(style);
  67617. // Loading img
  67618. var imgBack = new Image();
  67619. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  67620. imgBack.style.position = "absolute";
  67621. imgBack.style.left = "50%";
  67622. imgBack.style.top = "50%";
  67623. imgBack.style.marginLeft = "-60px";
  67624. imgBack.style.marginTop = "-60px";
  67625. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67626. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67627. imgBack.style.transformOrigin = "50% 50%";
  67628. imgBack.style.webkitTransformOrigin = "50% 50%";
  67629. this._loadingDiv.appendChild(imgBack);
  67630. this._resizeLoadingUI();
  67631. window.addEventListener("resize", this._resizeLoadingUI);
  67632. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67633. document.body.appendChild(this._loadingDiv);
  67634. this._loadingDiv.style.opacity = "1";
  67635. };
  67636. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67637. var _this = this;
  67638. if (!this._loadingDiv) {
  67639. return;
  67640. }
  67641. var onTransitionEnd = function () {
  67642. if (!_this._loadingDiv) {
  67643. return;
  67644. }
  67645. document.body.removeChild(_this._loadingDiv);
  67646. window.removeEventListener("resize", _this._resizeLoadingUI);
  67647. _this._loadingDiv = null;
  67648. };
  67649. this._loadingDiv.style.opacity = "0";
  67650. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67651. };
  67652. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67653. set: function (text) {
  67654. this._loadingText = text;
  67655. if (this._loadingTextDiv) {
  67656. this._loadingTextDiv.innerHTML = this._loadingText;
  67657. }
  67658. },
  67659. enumerable: true,
  67660. configurable: true
  67661. });
  67662. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67663. get: function () {
  67664. return this._loadingDivBackgroundColor;
  67665. },
  67666. set: function (color) {
  67667. this._loadingDivBackgroundColor = color;
  67668. if (!this._loadingDiv) {
  67669. return;
  67670. }
  67671. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67672. },
  67673. enumerable: true,
  67674. configurable: true
  67675. });
  67676. return DefaultLoadingScreen;
  67677. }());
  67678. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67679. })(BABYLON || (BABYLON = {}));
  67680. //# sourceMappingURL=babylon.loadingScreen.js.map
  67681. var BABYLON;
  67682. (function (BABYLON) {
  67683. var SceneLoaderProgressEvent = /** @class */ (function () {
  67684. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67685. this.lengthComputable = lengthComputable;
  67686. this.loaded = loaded;
  67687. this.total = total;
  67688. }
  67689. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67690. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67691. };
  67692. return SceneLoaderProgressEvent;
  67693. }());
  67694. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67695. var SceneLoader = /** @class */ (function () {
  67696. function SceneLoader() {
  67697. }
  67698. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67699. get: function () {
  67700. return 0;
  67701. },
  67702. enumerable: true,
  67703. configurable: true
  67704. });
  67705. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67706. get: function () {
  67707. return 1;
  67708. },
  67709. enumerable: true,
  67710. configurable: true
  67711. });
  67712. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67713. get: function () {
  67714. return 2;
  67715. },
  67716. enumerable: true,
  67717. configurable: true
  67718. });
  67719. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67720. get: function () {
  67721. return 3;
  67722. },
  67723. enumerable: true,
  67724. configurable: true
  67725. });
  67726. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67727. get: function () {
  67728. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67729. },
  67730. set: function (value) {
  67731. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67732. },
  67733. enumerable: true,
  67734. configurable: true
  67735. });
  67736. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67737. get: function () {
  67738. return SceneLoader._ShowLoadingScreen;
  67739. },
  67740. set: function (value) {
  67741. SceneLoader._ShowLoadingScreen = value;
  67742. },
  67743. enumerable: true,
  67744. configurable: true
  67745. });
  67746. Object.defineProperty(SceneLoader, "loggingLevel", {
  67747. get: function () {
  67748. return SceneLoader._loggingLevel;
  67749. },
  67750. set: function (value) {
  67751. SceneLoader._loggingLevel = value;
  67752. },
  67753. enumerable: true,
  67754. configurable: true
  67755. });
  67756. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67757. get: function () {
  67758. return SceneLoader._CleanBoneMatrixWeights;
  67759. },
  67760. set: function (value) {
  67761. SceneLoader._CleanBoneMatrixWeights = value;
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. SceneLoader._getDefaultPlugin = function () {
  67767. return SceneLoader._registeredPlugins[".babylon"];
  67768. };
  67769. SceneLoader._getPluginForExtension = function (extension) {
  67770. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67771. if (registeredPlugin) {
  67772. return registeredPlugin;
  67773. }
  67774. 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");
  67775. return SceneLoader._getDefaultPlugin();
  67776. };
  67777. SceneLoader._getPluginForDirectLoad = function (data) {
  67778. for (var extension in SceneLoader._registeredPlugins) {
  67779. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67780. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67781. return SceneLoader._registeredPlugins[extension];
  67782. }
  67783. }
  67784. return SceneLoader._getDefaultPlugin();
  67785. };
  67786. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67787. if (sceneFilename.name) {
  67788. sceneFilename = sceneFilename.name;
  67789. }
  67790. var queryStringPosition = sceneFilename.indexOf("?");
  67791. if (queryStringPosition !== -1) {
  67792. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67793. }
  67794. var dotPosition = sceneFilename.lastIndexOf(".");
  67795. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67796. return SceneLoader._getPluginForExtension(extension);
  67797. };
  67798. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67799. SceneLoader._getDirectLoad = function (sceneFilename) {
  67800. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67801. return sceneFilename.substr(5);
  67802. }
  67803. return null;
  67804. };
  67805. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67806. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67807. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67808. var plugin;
  67809. if (registeredPlugin.plugin.createPlugin) {
  67810. plugin = registeredPlugin.plugin.createPlugin();
  67811. }
  67812. else {
  67813. plugin = registeredPlugin.plugin;
  67814. }
  67815. var useArrayBuffer = registeredPlugin.isBinary;
  67816. var database;
  67817. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67818. var dataCallback = function (data, responseURL) {
  67819. if (scene.isDisposed) {
  67820. onError("Scene has been disposed");
  67821. return;
  67822. }
  67823. scene.database = database;
  67824. onSuccess(plugin, data, responseURL);
  67825. };
  67826. var request = null;
  67827. var pluginDisposed = false;
  67828. var onDisposeObservable = plugin.onDisposeObservable;
  67829. if (onDisposeObservable) {
  67830. onDisposeObservable.add(function () {
  67831. pluginDisposed = true;
  67832. if (request) {
  67833. request.abort();
  67834. request = null;
  67835. }
  67836. onDispose();
  67837. });
  67838. }
  67839. var manifestChecked = function () {
  67840. if (pluginDisposed) {
  67841. return;
  67842. }
  67843. var url = rootUrl + sceneFilename;
  67844. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67845. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67846. } : undefined, database, useArrayBuffer, function (request, exception) {
  67847. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67848. });
  67849. };
  67850. if (directLoad) {
  67851. dataCallback(directLoad);
  67852. return plugin;
  67853. }
  67854. if (rootUrl.indexOf("file:") === -1) {
  67855. var engine = scene.getEngine();
  67856. var canUseOfflineSupport = engine.enableOfflineSupport;
  67857. if (canUseOfflineSupport) {
  67858. // Also check for exceptions
  67859. var exceptionFound = false;
  67860. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67861. var regex = _a[_i];
  67862. if (regex.test(rootUrl + sceneFilename)) {
  67863. exceptionFound = true;
  67864. break;
  67865. }
  67866. }
  67867. canUseOfflineSupport = !exceptionFound;
  67868. }
  67869. if (canUseOfflineSupport) {
  67870. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67871. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67872. }
  67873. else {
  67874. manifestChecked();
  67875. }
  67876. }
  67877. // Loading file from disk via input file or drag'n'drop
  67878. else {
  67879. var fileOrString = sceneFilename;
  67880. if (fileOrString.name) { // File
  67881. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67882. }
  67883. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67884. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67885. }
  67886. else {
  67887. onError("Unable to find file named " + sceneFilename);
  67888. }
  67889. }
  67890. return plugin;
  67891. };
  67892. // Public functions
  67893. SceneLoader.GetPluginForExtension = function (extension) {
  67894. return SceneLoader._getPluginForExtension(extension).plugin;
  67895. };
  67896. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67897. return !!SceneLoader._registeredPlugins[extension];
  67898. };
  67899. SceneLoader.RegisterPlugin = function (plugin) {
  67900. if (typeof plugin.extensions === "string") {
  67901. var extension = plugin.extensions;
  67902. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67903. plugin: plugin,
  67904. isBinary: false
  67905. };
  67906. }
  67907. else {
  67908. var extensions = plugin.extensions;
  67909. Object.keys(extensions).forEach(function (extension) {
  67910. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67911. plugin: plugin,
  67912. isBinary: extensions[extension].isBinary
  67913. };
  67914. });
  67915. }
  67916. };
  67917. /**
  67918. * Import meshes into a scene
  67919. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67920. * @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)
  67921. * @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)
  67922. * @param scene the instance of BABYLON.Scene to append to
  67923. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67924. * @param onProgress a callback with a progress event for each file being loaded
  67925. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67926. * @param pluginExtension the extension used to determine the plugin
  67927. * @returns The loaded plugin
  67928. */
  67929. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67930. if (sceneFilename === void 0) { sceneFilename = ""; }
  67931. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67932. if (onSuccess === void 0) { onSuccess = null; }
  67933. if (onProgress === void 0) { onProgress = null; }
  67934. if (onError === void 0) { onError = null; }
  67935. if (pluginExtension === void 0) { pluginExtension = null; }
  67936. if (!scene) {
  67937. BABYLON.Tools.Error("No scene available to import mesh to");
  67938. return null;
  67939. }
  67940. if (!sceneFilename) {
  67941. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67942. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67943. }
  67944. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67945. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67946. return null;
  67947. }
  67948. var loadingToken = {};
  67949. scene._addPendingData(loadingToken);
  67950. var disposeHandler = function () {
  67951. scene._removePendingData(loadingToken);
  67952. };
  67953. var errorHandler = function (message, exception) {
  67954. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67955. if (onError) {
  67956. onError(scene, errorMessage, exception);
  67957. }
  67958. else {
  67959. BABYLON.Tools.Error(errorMessage);
  67960. // should the exception be thrown?
  67961. }
  67962. disposeHandler();
  67963. };
  67964. var progressHandler = onProgress ? function (event) {
  67965. try {
  67966. onProgress(event);
  67967. }
  67968. catch (e) {
  67969. errorHandler("Error in onProgress callback", e);
  67970. }
  67971. } : undefined;
  67972. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67973. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67974. if (onSuccess) {
  67975. try {
  67976. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67977. }
  67978. catch (e) {
  67979. errorHandler("Error in onSuccess callback", e);
  67980. }
  67981. }
  67982. scene._removePendingData(loadingToken);
  67983. };
  67984. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67985. if (plugin.rewriteRootURL) {
  67986. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67987. }
  67988. if (sceneFilename === "") {
  67989. if (sceneFilename === "") {
  67990. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67991. }
  67992. }
  67993. if (plugin.importMesh) {
  67994. var syncedPlugin = plugin;
  67995. var meshes = new Array();
  67996. var particleSystems = new Array();
  67997. var skeletons = new Array();
  67998. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67999. return;
  68000. }
  68001. scene.loadingPluginName = plugin.name;
  68002. successHandler(meshes, particleSystems, skeletons, []);
  68003. }
  68004. else {
  68005. var asyncedPlugin = plugin;
  68006. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  68007. scene.loadingPluginName = plugin.name;
  68008. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  68009. }).catch(function (error) {
  68010. errorHandler(error.message, error);
  68011. });
  68012. }
  68013. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68014. };
  68015. /**
  68016. * Import meshes into a scene
  68017. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  68018. * @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)
  68019. * @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)
  68020. * @param scene the instance of BABYLON.Scene to append to
  68021. * @param onProgress a callback with a progress event for each file being loaded
  68022. * @param pluginExtension the extension used to determine the plugin
  68023. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  68024. */
  68025. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68026. if (sceneFilename === void 0) { sceneFilename = ""; }
  68027. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68028. if (onProgress === void 0) { onProgress = null; }
  68029. if (pluginExtension === void 0) { pluginExtension = null; }
  68030. return new Promise(function (resolve, reject) {
  68031. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  68032. resolve({
  68033. meshes: meshes,
  68034. particleSystems: particleSystems,
  68035. skeletons: skeletons,
  68036. animationGroups: animationGroups
  68037. });
  68038. }, onProgress, function (scene, message, exception) {
  68039. reject(exception || new Error(message));
  68040. }, pluginExtension);
  68041. });
  68042. };
  68043. /**
  68044. * Load a scene
  68045. * @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)
  68046. * @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)
  68047. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68048. * @param onSuccess a callback with the scene when import succeeds
  68049. * @param onProgress a callback with a progress event for each file being loaded
  68050. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68051. * @param pluginExtension the extension used to determine the plugin
  68052. * @returns The loaded plugin
  68053. */
  68054. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  68055. if (onSuccess === void 0) { onSuccess = null; }
  68056. if (onProgress === void 0) { onProgress = null; }
  68057. if (onError === void 0) { onError = null; }
  68058. if (pluginExtension === void 0) { pluginExtension = null; }
  68059. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  68060. };
  68061. /**
  68062. * Load a scene
  68063. * @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)
  68064. * @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)
  68065. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68066. * @param onProgress a callback with a progress event for each file being loaded
  68067. * @param pluginExtension the extension used to determine the plugin
  68068. * @returns The loaded scene
  68069. */
  68070. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  68071. if (onProgress === void 0) { onProgress = null; }
  68072. if (pluginExtension === void 0) { pluginExtension = null; }
  68073. return new Promise(function (resolve, reject) {
  68074. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  68075. resolve(scene);
  68076. }, onProgress, function (scene, message, exception) {
  68077. reject(exception || new Error(message));
  68078. }, pluginExtension);
  68079. });
  68080. };
  68081. /**
  68082. * Append a scene
  68083. * @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)
  68084. * @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)
  68085. * @param scene is the instance of BABYLON.Scene to append to
  68086. * @param onSuccess a callback with the scene when import succeeds
  68087. * @param onProgress a callback with a progress event for each file being loaded
  68088. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68089. * @param pluginExtension the extension used to determine the plugin
  68090. * @returns The loaded plugin
  68091. */
  68092. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68093. if (sceneFilename === void 0) { sceneFilename = ""; }
  68094. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68095. if (onSuccess === void 0) { onSuccess = null; }
  68096. if (onProgress === void 0) { onProgress = null; }
  68097. if (onError === void 0) { onError = null; }
  68098. if (pluginExtension === void 0) { pluginExtension = null; }
  68099. if (!scene) {
  68100. BABYLON.Tools.Error("No scene available to append to");
  68101. return null;
  68102. }
  68103. if (!sceneFilename) {
  68104. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68105. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68106. }
  68107. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68108. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68109. return null;
  68110. }
  68111. if (SceneLoader.ShowLoadingScreen) {
  68112. scene.getEngine().displayLoadingUI();
  68113. }
  68114. var loadingToken = {};
  68115. scene._addPendingData(loadingToken);
  68116. var disposeHandler = function () {
  68117. scene._removePendingData(loadingToken);
  68118. scene.getEngine().hideLoadingUI();
  68119. };
  68120. var errorHandler = function (message, exception) {
  68121. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68122. if (onError) {
  68123. onError(scene, errorMessage, exception);
  68124. }
  68125. else {
  68126. BABYLON.Tools.Error(errorMessage);
  68127. // should the exception be thrown?
  68128. }
  68129. disposeHandler();
  68130. };
  68131. var progressHandler = onProgress ? function (event) {
  68132. try {
  68133. onProgress(event);
  68134. }
  68135. catch (e) {
  68136. errorHandler("Error in onProgress callback", e);
  68137. }
  68138. } : undefined;
  68139. var successHandler = function () {
  68140. if (onSuccess) {
  68141. try {
  68142. onSuccess(scene);
  68143. }
  68144. catch (e) {
  68145. errorHandler("Error in onSuccess callback", e);
  68146. }
  68147. }
  68148. scene._removePendingData(loadingToken);
  68149. };
  68150. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68151. if (sceneFilename === "") {
  68152. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68153. }
  68154. if (plugin.load) {
  68155. var syncedPlugin = plugin;
  68156. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  68157. return;
  68158. }
  68159. scene.loadingPluginName = plugin.name;
  68160. successHandler();
  68161. }
  68162. else {
  68163. var asyncedPlugin = plugin;
  68164. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68165. scene.loadingPluginName = plugin.name;
  68166. successHandler();
  68167. }).catch(function (error) {
  68168. errorHandler(error.message, error);
  68169. });
  68170. }
  68171. if (SceneLoader.ShowLoadingScreen) {
  68172. scene.executeWhenReady(function () {
  68173. scene.getEngine().hideLoadingUI();
  68174. });
  68175. }
  68176. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68177. };
  68178. /**
  68179. * Append a scene
  68180. * @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)
  68181. * @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)
  68182. * @param scene is the instance of BABYLON.Scene to append to
  68183. * @param onProgress a callback with a progress event for each file being loaded
  68184. * @param pluginExtension the extension used to determine the plugin
  68185. * @returns The given scene
  68186. */
  68187. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68188. if (sceneFilename === void 0) { sceneFilename = ""; }
  68189. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68190. if (onProgress === void 0) { onProgress = null; }
  68191. if (pluginExtension === void 0) { pluginExtension = null; }
  68192. return new Promise(function (resolve, reject) {
  68193. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68194. resolve(scene);
  68195. }, onProgress, function (scene, message, exception) {
  68196. reject(exception || new Error(message));
  68197. }, pluginExtension);
  68198. });
  68199. };
  68200. /**
  68201. * Load a scene into an asset container
  68202. * @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)
  68203. * @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)
  68204. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68205. * @param onSuccess a callback with the scene when import succeeds
  68206. * @param onProgress a callback with a progress event for each file being loaded
  68207. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68208. * @param pluginExtension the extension used to determine the plugin
  68209. * @returns The loaded plugin
  68210. */
  68211. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68212. if (sceneFilename === void 0) { sceneFilename = ""; }
  68213. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68214. if (onSuccess === void 0) { onSuccess = null; }
  68215. if (onProgress === void 0) { onProgress = null; }
  68216. if (onError === void 0) { onError = null; }
  68217. if (pluginExtension === void 0) { pluginExtension = null; }
  68218. if (!scene) {
  68219. BABYLON.Tools.Error("No scene available to load asset container to");
  68220. return null;
  68221. }
  68222. if (!sceneFilename) {
  68223. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68224. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68225. }
  68226. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68227. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68228. return null;
  68229. }
  68230. var loadingToken = {};
  68231. scene._addPendingData(loadingToken);
  68232. var disposeHandler = function () {
  68233. scene._removePendingData(loadingToken);
  68234. };
  68235. var errorHandler = function (message, exception) {
  68236. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68237. if (onError) {
  68238. onError(scene, errorMessage, exception);
  68239. }
  68240. else {
  68241. BABYLON.Tools.Error(errorMessage);
  68242. // should the exception be thrown?
  68243. }
  68244. disposeHandler();
  68245. };
  68246. var progressHandler = onProgress ? function (event) {
  68247. try {
  68248. onProgress(event);
  68249. }
  68250. catch (e) {
  68251. errorHandler("Error in onProgress callback", e);
  68252. }
  68253. } : undefined;
  68254. var successHandler = function (assets) {
  68255. if (onSuccess) {
  68256. try {
  68257. onSuccess(assets);
  68258. }
  68259. catch (e) {
  68260. errorHandler("Error in onSuccess callback", e);
  68261. }
  68262. }
  68263. scene._removePendingData(loadingToken);
  68264. };
  68265. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68266. if (plugin.loadAssetContainer) {
  68267. var syncedPlugin = plugin;
  68268. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68269. if (!assetContainer) {
  68270. return;
  68271. }
  68272. scene.loadingPluginName = plugin.name;
  68273. successHandler(assetContainer);
  68274. }
  68275. else if (plugin.loadAssetContainerAsync) {
  68276. var asyncedPlugin = plugin;
  68277. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68278. scene.loadingPluginName = plugin.name;
  68279. successHandler(assetContainer);
  68280. }).catch(function (error) {
  68281. errorHandler(error.message, error);
  68282. });
  68283. }
  68284. else {
  68285. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68286. }
  68287. if (SceneLoader.ShowLoadingScreen) {
  68288. scene.executeWhenReady(function () {
  68289. scene.getEngine().hideLoadingUI();
  68290. });
  68291. }
  68292. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68293. };
  68294. /**
  68295. * Load a scene into an asset container
  68296. * @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)
  68297. * @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)
  68298. * @param scene is the instance of BABYLON.Scene to append to
  68299. * @param onProgress a callback with a progress event for each file being loaded
  68300. * @param pluginExtension the extension used to determine the plugin
  68301. * @returns The loaded asset container
  68302. */
  68303. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68304. if (sceneFilename === void 0) { sceneFilename = ""; }
  68305. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68306. if (onProgress === void 0) { onProgress = null; }
  68307. if (pluginExtension === void 0) { pluginExtension = null; }
  68308. return new Promise(function (resolve, reject) {
  68309. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68310. resolve(assetContainer);
  68311. }, onProgress, function (scene, message, exception) {
  68312. reject(exception || new Error(message));
  68313. }, pluginExtension);
  68314. });
  68315. };
  68316. // Flags
  68317. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68318. SceneLoader._ShowLoadingScreen = true;
  68319. SceneLoader._CleanBoneMatrixWeights = false;
  68320. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68321. // Members
  68322. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68323. SceneLoader._registeredPlugins = {};
  68324. return SceneLoader;
  68325. }());
  68326. BABYLON.SceneLoader = SceneLoader;
  68327. ;
  68328. })(BABYLON || (BABYLON = {}));
  68329. //# sourceMappingURL=babylon.sceneLoader.js.map
  68330. var BABYLON;
  68331. (function (BABYLON) {
  68332. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68333. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68334. var parsedMaterial = parsedData.materials[index];
  68335. if (parsedMaterial.id === id) {
  68336. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68337. }
  68338. }
  68339. return null;
  68340. };
  68341. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68342. for (var i in names) {
  68343. if (mesh.name === names[i]) {
  68344. hierarchyIds.push(mesh.id);
  68345. return true;
  68346. }
  68347. }
  68348. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68349. hierarchyIds.push(mesh.id);
  68350. return true;
  68351. }
  68352. return false;
  68353. };
  68354. var logOperation = function (operation, producer) {
  68355. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68356. };
  68357. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68358. if (addToScene === void 0) { addToScene = false; }
  68359. var container = new BABYLON.AssetContainer(scene);
  68360. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68361. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68362. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68363. // and avoid problems with multiple concurrent .babylon loads.
  68364. var log = "importScene has failed JSON parse";
  68365. try {
  68366. var parsedData = JSON.parse(data);
  68367. log = "";
  68368. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68369. var index;
  68370. var cache;
  68371. // Lights
  68372. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68373. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68374. var parsedLight = parsedData.lights[index];
  68375. var light = BABYLON.Light.Parse(parsedLight, scene);
  68376. if (light) {
  68377. container.lights.push(light);
  68378. log += (index === 0 ? "\n\tLights:" : "");
  68379. log += "\n\t\t" + light.toString(fullDetails);
  68380. }
  68381. }
  68382. }
  68383. // Animations
  68384. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68385. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68386. var parsedAnimation = parsedData.animations[index];
  68387. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68388. scene.animations.push(animation);
  68389. container.animations.push(animation);
  68390. log += (index === 0 ? "\n\tAnimations:" : "");
  68391. log += "\n\t\t" + animation.toString(fullDetails);
  68392. }
  68393. }
  68394. // Materials
  68395. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68396. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68397. var parsedMaterial = parsedData.materials[index];
  68398. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68399. container.materials.push(mat);
  68400. log += (index === 0 ? "\n\tMaterials:" : "");
  68401. log += "\n\t\t" + mat.toString(fullDetails);
  68402. }
  68403. }
  68404. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68405. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68406. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68407. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68408. container.multiMaterials.push(mmat);
  68409. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68410. log += "\n\t\t" + mmat.toString(fullDetails);
  68411. }
  68412. }
  68413. // Morph targets
  68414. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68415. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68416. var managerData = _a[_i];
  68417. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68418. }
  68419. }
  68420. // Skeletons
  68421. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68422. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68423. var parsedSkeleton = parsedData.skeletons[index];
  68424. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68425. container.skeletons.push(skeleton);
  68426. log += (index === 0 ? "\n\tSkeletons:" : "");
  68427. log += "\n\t\t" + skeleton.toString(fullDetails);
  68428. }
  68429. }
  68430. // Geometries
  68431. var geometries = parsedData.geometries;
  68432. if (geometries !== undefined && geometries !== null) {
  68433. var addedGeometry = new Array();
  68434. // Boxes
  68435. var boxes = geometries.boxes;
  68436. if (boxes !== undefined && boxes !== null) {
  68437. for (index = 0, cache = boxes.length; index < cache; index++) {
  68438. var parsedBox = boxes[index];
  68439. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68440. }
  68441. }
  68442. // Spheres
  68443. var spheres = geometries.spheres;
  68444. if (spheres !== undefined && spheres !== null) {
  68445. for (index = 0, cache = spheres.length; index < cache; index++) {
  68446. var parsedSphere = spheres[index];
  68447. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68448. }
  68449. }
  68450. // Cylinders
  68451. var cylinders = geometries.cylinders;
  68452. if (cylinders !== undefined && cylinders !== null) {
  68453. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68454. var parsedCylinder = cylinders[index];
  68455. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68456. }
  68457. }
  68458. // Toruses
  68459. var toruses = geometries.toruses;
  68460. if (toruses !== undefined && toruses !== null) {
  68461. for (index = 0, cache = toruses.length; index < cache; index++) {
  68462. var parsedTorus = toruses[index];
  68463. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68464. }
  68465. }
  68466. // Grounds
  68467. var grounds = geometries.grounds;
  68468. if (grounds !== undefined && grounds !== null) {
  68469. for (index = 0, cache = grounds.length; index < cache; index++) {
  68470. var parsedGround = grounds[index];
  68471. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68472. }
  68473. }
  68474. // Planes
  68475. var planes = geometries.planes;
  68476. if (planes !== undefined && planes !== null) {
  68477. for (index = 0, cache = planes.length; index < cache; index++) {
  68478. var parsedPlane = planes[index];
  68479. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68480. }
  68481. }
  68482. // TorusKnots
  68483. var torusKnots = geometries.torusKnots;
  68484. if (torusKnots !== undefined && torusKnots !== null) {
  68485. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68486. var parsedTorusKnot = torusKnots[index];
  68487. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68488. }
  68489. }
  68490. // VertexData
  68491. var vertexData = geometries.vertexData;
  68492. if (vertexData !== undefined && vertexData !== null) {
  68493. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68494. var parsedVertexData = vertexData[index];
  68495. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68496. }
  68497. }
  68498. addedGeometry.forEach(function (g) {
  68499. if (g) {
  68500. container.geometries.push(g);
  68501. }
  68502. });
  68503. }
  68504. // Transform nodes
  68505. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68506. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68507. var parsedTransformNode = parsedData.transformNodes[index];
  68508. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68509. container.transformNodes.push(node);
  68510. }
  68511. }
  68512. // Meshes
  68513. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68514. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68515. var parsedMesh = parsedData.meshes[index];
  68516. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68517. container.meshes.push(mesh);
  68518. log += (index === 0 ? "\n\tMeshes:" : "");
  68519. log += "\n\t\t" + mesh.toString(fullDetails);
  68520. }
  68521. }
  68522. // Cameras
  68523. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68524. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68525. var parsedCamera = parsedData.cameras[index];
  68526. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68527. container.cameras.push(camera);
  68528. log += (index === 0 ? "\n\tCameras:" : "");
  68529. log += "\n\t\t" + camera.toString(fullDetails);
  68530. }
  68531. }
  68532. // Browsing all the graph to connect the dots
  68533. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68534. var camera = scene.cameras[index];
  68535. if (camera._waitingParentId) {
  68536. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68537. camera._waitingParentId = null;
  68538. }
  68539. }
  68540. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68541. var light_1 = scene.lights[index];
  68542. if (light_1 && light_1._waitingParentId) {
  68543. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68544. light_1._waitingParentId = null;
  68545. }
  68546. }
  68547. // Sounds
  68548. // TODO: add sound
  68549. var loadedSounds = [];
  68550. var loadedSound;
  68551. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68552. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68553. var parsedSound = parsedData.sounds[index];
  68554. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68555. if (!parsedSound.url)
  68556. parsedSound.url = parsedSound.name;
  68557. if (!loadedSounds[parsedSound.url]) {
  68558. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68559. loadedSounds[parsedSound.url] = loadedSound;
  68560. container.sounds.push(loadedSound);
  68561. }
  68562. else {
  68563. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68564. }
  68565. }
  68566. else {
  68567. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68568. }
  68569. }
  68570. }
  68571. loadedSounds = [];
  68572. // Connect parents & children and parse actions
  68573. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68574. var transformNode = scene.transformNodes[index];
  68575. if (transformNode._waitingParentId) {
  68576. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68577. transformNode._waitingParentId = null;
  68578. }
  68579. }
  68580. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68581. var mesh = scene.meshes[index];
  68582. if (mesh._waitingParentId) {
  68583. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68584. mesh._waitingParentId = null;
  68585. }
  68586. if (mesh._waitingActions) {
  68587. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68588. mesh._waitingActions = null;
  68589. }
  68590. }
  68591. // freeze world matrix application
  68592. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68593. var currentMesh = scene.meshes[index];
  68594. if (currentMesh._waitingFreezeWorldMatrix) {
  68595. currentMesh.freezeWorldMatrix();
  68596. currentMesh._waitingFreezeWorldMatrix = null;
  68597. }
  68598. else {
  68599. currentMesh.computeWorldMatrix(true);
  68600. }
  68601. }
  68602. // Particles Systems
  68603. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68604. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68605. var parsedParticleSystem = parsedData.particleSystems[index];
  68606. if (parsedParticleSystem.activeParticleCount) {
  68607. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68608. container.particleSystems.push(ps);
  68609. }
  68610. else {
  68611. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68612. container.particleSystems.push(ps);
  68613. }
  68614. }
  68615. }
  68616. // Shadows
  68617. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68618. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68619. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68620. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68621. // SG would be available on their associated lights
  68622. }
  68623. }
  68624. // Lights exclusions / inclusions
  68625. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68626. var light_2 = scene.lights[index];
  68627. // Excluded check
  68628. if (light_2._excludedMeshesIds.length > 0) {
  68629. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68630. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68631. if (excludedMesh) {
  68632. light_2.excludedMeshes.push(excludedMesh);
  68633. }
  68634. }
  68635. light_2._excludedMeshesIds = [];
  68636. }
  68637. // Included check
  68638. if (light_2._includedOnlyMeshesIds.length > 0) {
  68639. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68640. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68641. if (includedOnlyMesh) {
  68642. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68643. }
  68644. }
  68645. light_2._includedOnlyMeshesIds = [];
  68646. }
  68647. }
  68648. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68649. // Actions (scene)
  68650. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68651. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68652. }
  68653. if (!addToScene) {
  68654. container.removeAllFromScene();
  68655. }
  68656. }
  68657. catch (err) {
  68658. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68659. if (onError) {
  68660. onError(msg, err);
  68661. }
  68662. else {
  68663. BABYLON.Tools.Log(msg);
  68664. throw err;
  68665. }
  68666. }
  68667. finally {
  68668. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68669. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68670. }
  68671. }
  68672. return container;
  68673. };
  68674. BABYLON.SceneLoader.RegisterPlugin({
  68675. name: "babylon.js",
  68676. extensions: ".babylon",
  68677. canDirectLoad: function (data) {
  68678. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68679. return true;
  68680. }
  68681. return false;
  68682. },
  68683. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68684. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68685. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68686. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68687. // and avoid problems with multiple concurrent .babylon loads.
  68688. var log = "importMesh has failed JSON parse";
  68689. try {
  68690. var parsedData = JSON.parse(data);
  68691. log = "";
  68692. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68693. if (!meshesNames) {
  68694. meshesNames = null;
  68695. }
  68696. else if (!Array.isArray(meshesNames)) {
  68697. meshesNames = [meshesNames];
  68698. }
  68699. var hierarchyIds = new Array();
  68700. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68701. var loadedSkeletonsIds = [];
  68702. var loadedMaterialsIds = [];
  68703. var index;
  68704. var cache;
  68705. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68706. var parsedMesh = parsedData.meshes[index];
  68707. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68708. if (meshesNames !== null) {
  68709. // Remove found mesh name from list.
  68710. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68711. }
  68712. //Geometry?
  68713. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68714. //does the file contain geometries?
  68715. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68716. //find the correct geometry and add it to the scene
  68717. var found = false;
  68718. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68719. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68720. return;
  68721. }
  68722. else {
  68723. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68724. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68725. switch (geometryType) {
  68726. case "boxes":
  68727. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68728. break;
  68729. case "spheres":
  68730. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68731. break;
  68732. case "cylinders":
  68733. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68734. break;
  68735. case "toruses":
  68736. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68737. break;
  68738. case "grounds":
  68739. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68740. break;
  68741. case "planes":
  68742. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68743. break;
  68744. case "torusKnots":
  68745. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68746. break;
  68747. case "vertexData":
  68748. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68749. break;
  68750. }
  68751. found = true;
  68752. }
  68753. });
  68754. }
  68755. });
  68756. if (found === false) {
  68757. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68758. }
  68759. }
  68760. }
  68761. // Material ?
  68762. if (parsedMesh.materialId) {
  68763. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68764. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68765. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68766. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68767. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68768. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68769. var subMatId = parsedMultiMaterial.materials[matIndex];
  68770. loadedMaterialsIds.push(subMatId);
  68771. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68772. if (mat) {
  68773. log += "\n\tMaterial " + mat.toString(fullDetails);
  68774. }
  68775. }
  68776. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68777. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68778. if (mmat) {
  68779. materialFound = true;
  68780. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68781. }
  68782. break;
  68783. }
  68784. }
  68785. }
  68786. if (materialFound === false) {
  68787. loadedMaterialsIds.push(parsedMesh.materialId);
  68788. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68789. if (!mat) {
  68790. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68791. }
  68792. else {
  68793. log += "\n\tMaterial " + mat.toString(fullDetails);
  68794. }
  68795. }
  68796. }
  68797. // Skeleton ?
  68798. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68799. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68800. if (skeletonAlreadyLoaded === false) {
  68801. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68802. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68803. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68804. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68805. skeletons.push(skeleton);
  68806. loadedSkeletonsIds.push(parsedSkeleton.id);
  68807. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68808. }
  68809. }
  68810. }
  68811. }
  68812. // Morph targets ?
  68813. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68814. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68815. var managerData = _a[_i];
  68816. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68817. }
  68818. }
  68819. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68820. meshes.push(mesh);
  68821. log += "\n\tMesh " + mesh.toString(fullDetails);
  68822. }
  68823. }
  68824. // Connecting parents
  68825. var currentMesh;
  68826. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68827. currentMesh = scene.meshes[index];
  68828. if (currentMesh._waitingParentId) {
  68829. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68830. currentMesh._waitingParentId = null;
  68831. }
  68832. }
  68833. // freeze and compute world matrix application
  68834. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68835. currentMesh = scene.meshes[index];
  68836. if (currentMesh._waitingFreezeWorldMatrix) {
  68837. currentMesh.freezeWorldMatrix();
  68838. currentMesh._waitingFreezeWorldMatrix = null;
  68839. }
  68840. else {
  68841. currentMesh.computeWorldMatrix(true);
  68842. }
  68843. }
  68844. }
  68845. // Particles
  68846. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68847. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68848. var parsedParticleSystem = parsedData.particleSystems[index];
  68849. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68850. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68851. }
  68852. }
  68853. }
  68854. return true;
  68855. }
  68856. catch (err) {
  68857. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68858. if (onError) {
  68859. onError(msg, err);
  68860. }
  68861. else {
  68862. BABYLON.Tools.Log(msg);
  68863. throw err;
  68864. }
  68865. }
  68866. finally {
  68867. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68868. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68869. }
  68870. }
  68871. return false;
  68872. },
  68873. load: function (scene, data, rootUrl, onError) {
  68874. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68875. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68876. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68877. // and avoid problems with multiple concurrent .babylon loads.
  68878. var log = "importScene has failed JSON parse";
  68879. try {
  68880. var parsedData = JSON.parse(data);
  68881. log = "";
  68882. // Scene
  68883. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68884. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68885. }
  68886. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68887. scene.autoClear = parsedData.autoClear;
  68888. }
  68889. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68890. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68891. }
  68892. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68893. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68894. }
  68895. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68896. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68897. }
  68898. // Fog
  68899. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68900. scene.fogMode = parsedData.fogMode;
  68901. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68902. scene.fogStart = parsedData.fogStart;
  68903. scene.fogEnd = parsedData.fogEnd;
  68904. scene.fogDensity = parsedData.fogDensity;
  68905. log += "\tFog mode for scene: ";
  68906. switch (scene.fogMode) {
  68907. // getters not compiling, so using hardcoded
  68908. case 1:
  68909. log += "exp\n";
  68910. break;
  68911. case 2:
  68912. log += "exp2\n";
  68913. break;
  68914. case 3:
  68915. log += "linear\n";
  68916. break;
  68917. }
  68918. }
  68919. //Physics
  68920. if (parsedData.physicsEnabled) {
  68921. var physicsPlugin;
  68922. if (parsedData.physicsEngine === "cannon") {
  68923. physicsPlugin = new BABYLON.CannonJSPlugin();
  68924. }
  68925. else if (parsedData.physicsEngine === "oimo") {
  68926. physicsPlugin = new BABYLON.OimoJSPlugin();
  68927. }
  68928. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68929. //else - default engine, which is currently oimo
  68930. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68931. scene.enablePhysics(physicsGravity, physicsPlugin);
  68932. }
  68933. // Metadata
  68934. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68935. scene.metadata = parsedData.metadata;
  68936. }
  68937. //collisions, if defined. otherwise, default is true
  68938. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68939. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68940. }
  68941. scene.workerCollisions = !!parsedData.workerCollisions;
  68942. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68943. if (!container) {
  68944. return false;
  68945. }
  68946. if (parsedData.autoAnimate) {
  68947. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68948. }
  68949. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68950. scene.setActiveCameraByID(parsedData.activeCameraID);
  68951. }
  68952. // Environment texture
  68953. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68954. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68955. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68956. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68957. if (parsedData.environmentTextureRotationY) {
  68958. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68959. }
  68960. scene.environmentTexture = hdrTexture;
  68961. }
  68962. else {
  68963. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68964. if (parsedData.environmentTextureRotationY) {
  68965. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68966. }
  68967. scene.environmentTexture = cubeTexture;
  68968. }
  68969. if (parsedData.createDefaultSkybox === true) {
  68970. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68971. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68972. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68973. }
  68974. }
  68975. // Finish
  68976. return true;
  68977. }
  68978. catch (err) {
  68979. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68980. if (onError) {
  68981. onError(msg, err);
  68982. }
  68983. else {
  68984. BABYLON.Tools.Log(msg);
  68985. throw err;
  68986. }
  68987. }
  68988. finally {
  68989. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68990. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68991. }
  68992. }
  68993. return false;
  68994. },
  68995. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68996. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68997. return container;
  68998. }
  68999. });
  69000. })(BABYLON || (BABYLON = {}));
  69001. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  69002. var BABYLON;
  69003. (function (BABYLON) {
  69004. var FilesInput = /** @class */ (function () {
  69005. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  69006. this.onProcessFileCallback = function () { return true; };
  69007. this._engine = engine;
  69008. this._currentScene = scene;
  69009. this._sceneLoadedCallback = sceneLoadedCallback;
  69010. this._progressCallback = progressCallback;
  69011. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  69012. this._textureLoadingCallback = textureLoadingCallback;
  69013. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  69014. this._onReloadCallback = onReloadCallback;
  69015. this._errorCallback = errorCallback;
  69016. }
  69017. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  69018. var _this = this;
  69019. if (elementToMonitor) {
  69020. this._elementToMonitor = elementToMonitor;
  69021. this._dragEnterHandler = function (e) { _this.drag(e); };
  69022. this._dragOverHandler = function (e) { _this.drag(e); };
  69023. this._dropHandler = function (e) { _this.drop(e); };
  69024. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  69025. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  69026. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  69027. }
  69028. };
  69029. FilesInput.prototype.dispose = function () {
  69030. if (!this._elementToMonitor) {
  69031. return;
  69032. }
  69033. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  69034. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  69035. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  69036. };
  69037. FilesInput.prototype.renderFunction = function () {
  69038. if (this._additionalRenderLoopLogicCallback) {
  69039. this._additionalRenderLoopLogicCallback();
  69040. }
  69041. if (this._currentScene) {
  69042. if (this._textureLoadingCallback) {
  69043. var remaining = this._currentScene.getWaitingItemsCount();
  69044. if (remaining > 0) {
  69045. this._textureLoadingCallback(remaining);
  69046. }
  69047. }
  69048. this._currentScene.render();
  69049. }
  69050. };
  69051. FilesInput.prototype.drag = function (e) {
  69052. e.stopPropagation();
  69053. e.preventDefault();
  69054. };
  69055. FilesInput.prototype.drop = function (eventDrop) {
  69056. eventDrop.stopPropagation();
  69057. eventDrop.preventDefault();
  69058. this.loadFiles(eventDrop);
  69059. };
  69060. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  69061. var _this = this;
  69062. var reader = folder.createReader();
  69063. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  69064. reader.readEntries(function (entries) {
  69065. remaining.count += entries.length;
  69066. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  69067. var entry = entries_1[_i];
  69068. if (entry.isFile) {
  69069. entry.file(function (file) {
  69070. file.correctName = relativePath + file.name;
  69071. files.push(file);
  69072. if (--remaining.count === 0) {
  69073. callback();
  69074. }
  69075. });
  69076. }
  69077. else if (entry.isDirectory) {
  69078. _this._traverseFolder(entry, files, remaining, callback);
  69079. }
  69080. }
  69081. if (--remaining.count) {
  69082. callback();
  69083. }
  69084. });
  69085. };
  69086. FilesInput.prototype._processFiles = function (files) {
  69087. for (var i = 0; i < files.length; i++) {
  69088. var name = files[i].correctName.toLowerCase();
  69089. var extension = name.split('.').pop();
  69090. if (!this.onProcessFileCallback(files[i], name, extension)) {
  69091. continue;
  69092. }
  69093. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  69094. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  69095. this._sceneFileToLoad = files[i];
  69096. }
  69097. else {
  69098. FilesInput.FilesToLoad[name] = files[i];
  69099. }
  69100. }
  69101. };
  69102. FilesInput.prototype.loadFiles = function (event) {
  69103. var _this = this;
  69104. if (this._startingProcessingFilesCallback)
  69105. this._startingProcessingFilesCallback();
  69106. // Handling data transfer via drag'n'drop
  69107. if (event && event.dataTransfer && event.dataTransfer.files) {
  69108. this._filesToLoad = event.dataTransfer.files;
  69109. }
  69110. // Handling files from input files
  69111. if (event && event.target && event.target.files) {
  69112. this._filesToLoad = event.target.files;
  69113. }
  69114. if (this._filesToLoad && this._filesToLoad.length > 0) {
  69115. var files_1 = new Array();
  69116. var folders = [];
  69117. var items = event.dataTransfer ? event.dataTransfer.items : null;
  69118. for (var i = 0; i < this._filesToLoad.length; i++) {
  69119. var fileToLoad = this._filesToLoad[i];
  69120. var name_1 = fileToLoad.name.toLowerCase();
  69121. var entry = void 0;
  69122. fileToLoad.correctName = name_1;
  69123. if (items) {
  69124. var item = items[i];
  69125. if (item.getAsEntry) {
  69126. entry = item.getAsEntry();
  69127. }
  69128. else if (item.webkitGetAsEntry) {
  69129. entry = item.webkitGetAsEntry();
  69130. }
  69131. }
  69132. if (!entry) {
  69133. files_1.push(fileToLoad);
  69134. }
  69135. else {
  69136. if (entry.isDirectory) {
  69137. folders.push(entry);
  69138. }
  69139. else {
  69140. files_1.push(fileToLoad);
  69141. }
  69142. }
  69143. }
  69144. if (folders.length === 0) {
  69145. this._processFiles(files_1);
  69146. this._processReload();
  69147. }
  69148. else {
  69149. var remaining = { count: folders.length };
  69150. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  69151. var folder = folders_1[_i];
  69152. this._traverseFolder(folder, files_1, remaining, function () {
  69153. _this._processFiles(files_1);
  69154. if (remaining.count === 0) {
  69155. _this._processReload();
  69156. }
  69157. });
  69158. }
  69159. }
  69160. }
  69161. };
  69162. FilesInput.prototype._processReload = function () {
  69163. if (this._onReloadCallback) {
  69164. this._onReloadCallback(this._sceneFileToLoad);
  69165. }
  69166. else {
  69167. this.reload();
  69168. }
  69169. };
  69170. FilesInput.prototype.reload = function () {
  69171. var _this = this;
  69172. // If a scene file has been provided
  69173. if (this._sceneFileToLoad) {
  69174. if (this._currentScene) {
  69175. if (BABYLON.Tools.errorsCount > 0) {
  69176. BABYLON.Tools.ClearLogCache();
  69177. }
  69178. this._engine.stopRenderLoop();
  69179. }
  69180. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69181. if (_this._progressCallback) {
  69182. _this._progressCallback(progress);
  69183. }
  69184. }).then(function (scene) {
  69185. if (_this._currentScene) {
  69186. _this._currentScene.dispose();
  69187. }
  69188. _this._currentScene = scene;
  69189. if (_this._sceneLoadedCallback) {
  69190. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69191. }
  69192. // Wait for textures and shaders to be ready
  69193. _this._currentScene.executeWhenReady(function () {
  69194. _this._engine.runRenderLoop(function () {
  69195. _this.renderFunction();
  69196. });
  69197. });
  69198. }).catch(function (error) {
  69199. if (_this._errorCallback) {
  69200. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69201. }
  69202. });
  69203. }
  69204. else {
  69205. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69206. }
  69207. };
  69208. FilesInput.FilesToLoad = {};
  69209. return FilesInput;
  69210. }());
  69211. BABYLON.FilesInput = FilesInput;
  69212. })(BABYLON || (BABYLON = {}));
  69213. //# sourceMappingURL=babylon.filesInput.js.map
  69214. var BABYLON;
  69215. (function (BABYLON) {
  69216. /**
  69217. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69218. * The underlying implementation relies on an associative array to ensure the best performances.
  69219. * The value can be anything including 'null' but except 'undefined'
  69220. */
  69221. var StringDictionary = /** @class */ (function () {
  69222. function StringDictionary() {
  69223. this._count = 0;
  69224. this._data = {};
  69225. }
  69226. /**
  69227. * This will clear this dictionary and copy the content from the 'source' one.
  69228. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69229. * @param source the dictionary to take the content from and copy to this dictionary
  69230. */
  69231. StringDictionary.prototype.copyFrom = function (source) {
  69232. var _this = this;
  69233. this.clear();
  69234. source.forEach(function (t, v) { return _this.add(t, v); });
  69235. };
  69236. /**
  69237. * Get a value based from its key
  69238. * @param key the given key to get the matching value from
  69239. * @return the value if found, otherwise undefined is returned
  69240. */
  69241. StringDictionary.prototype.get = function (key) {
  69242. var val = this._data[key];
  69243. if (val !== undefined) {
  69244. return val;
  69245. }
  69246. return undefined;
  69247. };
  69248. /**
  69249. * Get a value from its key or add it if it doesn't exist.
  69250. * This method will ensure you that a given key/data will be present in the dictionary.
  69251. * @param key the given key to get the matching value from
  69252. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69253. * The factory will only be invoked if there's no data for the given key.
  69254. * @return the value corresponding to the key.
  69255. */
  69256. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69257. var val = this.get(key);
  69258. if (val !== undefined) {
  69259. return val;
  69260. }
  69261. val = factory(key);
  69262. if (val) {
  69263. this.add(key, val);
  69264. }
  69265. return val;
  69266. };
  69267. /**
  69268. * Get a value from its key if present in the dictionary otherwise add it
  69269. * @param key the key to get the value from
  69270. * @param val if there's no such key/value pair in the dictionary add it with this value
  69271. * @return the value corresponding to the key
  69272. */
  69273. StringDictionary.prototype.getOrAdd = function (key, val) {
  69274. var curVal = this.get(key);
  69275. if (curVal !== undefined) {
  69276. return curVal;
  69277. }
  69278. this.add(key, val);
  69279. return val;
  69280. };
  69281. /**
  69282. * Check if there's a given key in the dictionary
  69283. * @param key the key to check for
  69284. * @return true if the key is present, false otherwise
  69285. */
  69286. StringDictionary.prototype.contains = function (key) {
  69287. return this._data[key] !== undefined;
  69288. };
  69289. /**
  69290. * Add a new key and its corresponding value
  69291. * @param key the key to add
  69292. * @param value the value corresponding to the key
  69293. * @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
  69294. */
  69295. StringDictionary.prototype.add = function (key, value) {
  69296. if (this._data[key] !== undefined) {
  69297. return false;
  69298. }
  69299. this._data[key] = value;
  69300. ++this._count;
  69301. return true;
  69302. };
  69303. StringDictionary.prototype.set = function (key, value) {
  69304. if (this._data[key] === undefined) {
  69305. return false;
  69306. }
  69307. this._data[key] = value;
  69308. return true;
  69309. };
  69310. /**
  69311. * Get the element of the given key and remove it from the dictionary
  69312. * @param key
  69313. */
  69314. StringDictionary.prototype.getAndRemove = function (key) {
  69315. var val = this.get(key);
  69316. if (val !== undefined) {
  69317. delete this._data[key];
  69318. --this._count;
  69319. return val;
  69320. }
  69321. return null;
  69322. };
  69323. /**
  69324. * Remove a key/value from the dictionary.
  69325. * @param key the key to remove
  69326. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69327. */
  69328. StringDictionary.prototype.remove = function (key) {
  69329. if (this.contains(key)) {
  69330. delete this._data[key];
  69331. --this._count;
  69332. return true;
  69333. }
  69334. return false;
  69335. };
  69336. /**
  69337. * Clear the whole content of the dictionary
  69338. */
  69339. StringDictionary.prototype.clear = function () {
  69340. this._data = {};
  69341. this._count = 0;
  69342. };
  69343. Object.defineProperty(StringDictionary.prototype, "count", {
  69344. get: function () {
  69345. return this._count;
  69346. },
  69347. enumerable: true,
  69348. configurable: true
  69349. });
  69350. /**
  69351. * Execute a callback on each key/val of the dictionary.
  69352. * Note that you can remove any element in this dictionary in the callback implementation
  69353. * @param callback the callback to execute on a given key/value pair
  69354. */
  69355. StringDictionary.prototype.forEach = function (callback) {
  69356. for (var cur in this._data) {
  69357. var val = this._data[cur];
  69358. callback(cur, val);
  69359. }
  69360. };
  69361. /**
  69362. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69363. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69364. * Note that you can remove any element in this dictionary in the callback implementation
  69365. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69366. */
  69367. StringDictionary.prototype.first = function (callback) {
  69368. for (var cur in this._data) {
  69369. var val = this._data[cur];
  69370. var res = callback(cur, val);
  69371. if (res) {
  69372. return res;
  69373. }
  69374. }
  69375. return null;
  69376. };
  69377. return StringDictionary;
  69378. }());
  69379. BABYLON.StringDictionary = StringDictionary;
  69380. })(BABYLON || (BABYLON = {}));
  69381. //# sourceMappingURL=babylon.stringDictionary.js.map
  69382. var BABYLON;
  69383. (function (BABYLON) {
  69384. var Tags = /** @class */ (function () {
  69385. function Tags() {
  69386. }
  69387. Tags.EnableFor = function (obj) {
  69388. obj._tags = obj._tags || {};
  69389. obj.hasTags = function () {
  69390. return Tags.HasTags(obj);
  69391. };
  69392. obj.addTags = function (tagsString) {
  69393. return Tags.AddTagsTo(obj, tagsString);
  69394. };
  69395. obj.removeTags = function (tagsString) {
  69396. return Tags.RemoveTagsFrom(obj, tagsString);
  69397. };
  69398. obj.matchesTagsQuery = function (tagsQuery) {
  69399. return Tags.MatchesQuery(obj, tagsQuery);
  69400. };
  69401. };
  69402. Tags.DisableFor = function (obj) {
  69403. delete obj._tags;
  69404. delete obj.hasTags;
  69405. delete obj.addTags;
  69406. delete obj.removeTags;
  69407. delete obj.matchesTagsQuery;
  69408. };
  69409. Tags.HasTags = function (obj) {
  69410. if (!obj._tags) {
  69411. return false;
  69412. }
  69413. return !BABYLON.Tools.IsEmpty(obj._tags);
  69414. };
  69415. Tags.GetTags = function (obj, asString) {
  69416. if (asString === void 0) { asString = true; }
  69417. if (!obj._tags) {
  69418. return null;
  69419. }
  69420. if (asString) {
  69421. var tagsArray = [];
  69422. for (var tag in obj._tags) {
  69423. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69424. tagsArray.push(tag);
  69425. }
  69426. }
  69427. return tagsArray.join(" ");
  69428. }
  69429. else {
  69430. return obj._tags;
  69431. }
  69432. };
  69433. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69434. // a tag cannot start with '||', '&&', and '!'
  69435. // it cannot contain whitespaces
  69436. Tags.AddTagsTo = function (obj, tagsString) {
  69437. if (!tagsString) {
  69438. return;
  69439. }
  69440. if (typeof tagsString !== "string") {
  69441. return;
  69442. }
  69443. var tags = tagsString.split(" ");
  69444. tags.forEach(function (tag, index, array) {
  69445. Tags._AddTagTo(obj, tag);
  69446. });
  69447. };
  69448. Tags._AddTagTo = function (obj, tag) {
  69449. tag = tag.trim();
  69450. if (tag === "" || tag === "true" || tag === "false") {
  69451. return;
  69452. }
  69453. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69454. return;
  69455. }
  69456. Tags.EnableFor(obj);
  69457. obj._tags[tag] = true;
  69458. };
  69459. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69460. if (!Tags.HasTags(obj)) {
  69461. return;
  69462. }
  69463. var tags = tagsString.split(" ");
  69464. for (var t in tags) {
  69465. Tags._RemoveTagFrom(obj, tags[t]);
  69466. }
  69467. };
  69468. Tags._RemoveTagFrom = function (obj, tag) {
  69469. delete obj._tags[tag];
  69470. };
  69471. Tags.MatchesQuery = function (obj, tagsQuery) {
  69472. if (tagsQuery === undefined) {
  69473. return true;
  69474. }
  69475. if (tagsQuery === "") {
  69476. return Tags.HasTags(obj);
  69477. }
  69478. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69479. };
  69480. return Tags;
  69481. }());
  69482. BABYLON.Tags = Tags;
  69483. })(BABYLON || (BABYLON = {}));
  69484. //# sourceMappingURL=babylon.tags.js.map
  69485. var BABYLON;
  69486. (function (BABYLON) {
  69487. /**
  69488. * Class used to evalaute queries containing `and` and `or` operators
  69489. */
  69490. var AndOrNotEvaluator = /** @class */ (function () {
  69491. function AndOrNotEvaluator() {
  69492. }
  69493. /**
  69494. * Evaluate a query
  69495. * @param query defines the query to evaluate
  69496. * @param evaluateCallback defines the callback used to filter result
  69497. * @returns true if the query matches
  69498. */
  69499. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69500. if (!query.match(/\([^\(\)]*\)/g)) {
  69501. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69502. }
  69503. else {
  69504. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69505. // remove parenthesis
  69506. r = r.slice(1, r.length - 1);
  69507. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69508. });
  69509. }
  69510. if (query === "true") {
  69511. return true;
  69512. }
  69513. if (query === "false") {
  69514. return false;
  69515. }
  69516. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69517. };
  69518. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69519. evaluateCallback = evaluateCallback || (function (r) {
  69520. return r === "true" ? true : false;
  69521. });
  69522. var result;
  69523. var or = parenthesisContent.split("||");
  69524. for (var i in or) {
  69525. if (or.hasOwnProperty(i)) {
  69526. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69527. var and = ori.split("&&");
  69528. if (and.length > 1) {
  69529. for (var j = 0; j < and.length; ++j) {
  69530. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69531. if (andj !== "true" && andj !== "false") {
  69532. if (andj[0] === "!") {
  69533. result = !evaluateCallback(andj.substring(1));
  69534. }
  69535. else {
  69536. result = evaluateCallback(andj);
  69537. }
  69538. }
  69539. else {
  69540. result = andj === "true" ? true : false;
  69541. }
  69542. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69543. ori = "false";
  69544. break;
  69545. }
  69546. }
  69547. }
  69548. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69549. result = true;
  69550. break;
  69551. }
  69552. // result equals false (or undefined)
  69553. if (ori !== "true" && ori !== "false") {
  69554. if (ori[0] === "!") {
  69555. result = !evaluateCallback(ori.substring(1));
  69556. }
  69557. else {
  69558. result = evaluateCallback(ori);
  69559. }
  69560. }
  69561. else {
  69562. result = ori === "true" ? true : false;
  69563. }
  69564. }
  69565. }
  69566. // the whole parenthesis scope is replaced by 'true' or 'false'
  69567. return result ? "true" : "false";
  69568. };
  69569. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69570. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69571. // remove whitespaces
  69572. r = r.replace(/[\s]/g, function () { return ""; });
  69573. return r.length % 2 ? "!" : "";
  69574. });
  69575. booleanString = booleanString.trim();
  69576. if (booleanString === "!true") {
  69577. booleanString = "false";
  69578. }
  69579. else if (booleanString === "!false") {
  69580. booleanString = "true";
  69581. }
  69582. return booleanString;
  69583. };
  69584. return AndOrNotEvaluator;
  69585. }());
  69586. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69587. })(BABYLON || (BABYLON = {}));
  69588. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69589. var BABYLON;
  69590. (function (BABYLON) {
  69591. /**
  69592. * Class used to enable access to IndexedDB
  69593. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69594. */
  69595. var Database = /** @class */ (function () {
  69596. /**
  69597. * Creates a new Database
  69598. * @param urlToScene defines the url to load the scene
  69599. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69600. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69601. */
  69602. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69603. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69604. var _this = this;
  69605. // Handling various flavors of prefixed version of IndexedDB
  69606. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69607. this.callbackManifestChecked = callbackManifestChecked;
  69608. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69609. this.db = null;
  69610. this._enableSceneOffline = false;
  69611. this._enableTexturesOffline = false;
  69612. this.manifestVersionFound = 0;
  69613. this.mustUpdateRessources = false;
  69614. this.hasReachedQuota = false;
  69615. if (!Database.IDBStorageEnabled) {
  69616. this.callbackManifestChecked(true);
  69617. }
  69618. else {
  69619. if (disableManifestCheck) {
  69620. this._enableSceneOffline = true;
  69621. this._enableTexturesOffline = true;
  69622. this.manifestVersionFound = 1;
  69623. BABYLON.Tools.SetImmediate(function () {
  69624. _this.callbackManifestChecked(true);
  69625. });
  69626. }
  69627. else {
  69628. this._checkManifestFile();
  69629. }
  69630. }
  69631. }
  69632. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69633. /**
  69634. * Gets a boolean indicating if scene must be saved in the database
  69635. */
  69636. get: function () {
  69637. return this._enableSceneOffline;
  69638. },
  69639. enumerable: true,
  69640. configurable: true
  69641. });
  69642. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69643. /**
  69644. * Gets a boolean indicating if textures must be saved in the database
  69645. */
  69646. get: function () {
  69647. return this._enableTexturesOffline;
  69648. },
  69649. enumerable: true,
  69650. configurable: true
  69651. });
  69652. Database.prototype._checkManifestFile = function () {
  69653. var _this = this;
  69654. var noManifestFile = function () {
  69655. _this._enableSceneOffline = false;
  69656. _this._enableTexturesOffline = false;
  69657. _this.callbackManifestChecked(false);
  69658. };
  69659. var timeStampUsed = false;
  69660. var manifestURL = this.currentSceneUrl + ".manifest";
  69661. var xhr = new XMLHttpRequest();
  69662. if (navigator.onLine) {
  69663. // Adding a timestamp to by-pass browsers' cache
  69664. timeStampUsed = true;
  69665. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69666. }
  69667. xhr.open("GET", manifestURL, true);
  69668. xhr.addEventListener("load", function () {
  69669. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69670. try {
  69671. var manifestFile = JSON.parse(xhr.response);
  69672. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69673. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69674. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69675. _this.manifestVersionFound = manifestFile.version;
  69676. }
  69677. if (_this.callbackManifestChecked) {
  69678. _this.callbackManifestChecked(true);
  69679. }
  69680. }
  69681. catch (ex) {
  69682. noManifestFile();
  69683. }
  69684. }
  69685. else {
  69686. noManifestFile();
  69687. }
  69688. }, false);
  69689. xhr.addEventListener("error", function (event) {
  69690. if (timeStampUsed) {
  69691. timeStampUsed = false;
  69692. // Let's retry without the timeStamp
  69693. // It could fail when coupled with HTML5 Offline API
  69694. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69695. xhr.open("GET", retryManifestURL, true);
  69696. xhr.send();
  69697. }
  69698. else {
  69699. noManifestFile();
  69700. }
  69701. }, false);
  69702. try {
  69703. xhr.send();
  69704. }
  69705. catch (ex) {
  69706. BABYLON.Tools.Error("Error on XHR send request.");
  69707. this.callbackManifestChecked(false);
  69708. }
  69709. };
  69710. /**
  69711. * Open the database and make it available
  69712. * @param successCallback defines the callback to call on success
  69713. * @param errorCallback defines the callback to call on error
  69714. */
  69715. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69716. var _this = this;
  69717. var handleError = function () {
  69718. _this.isSupported = false;
  69719. if (errorCallback)
  69720. errorCallback();
  69721. };
  69722. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69723. // Your browser doesn't support IndexedDB
  69724. this.isSupported = false;
  69725. if (errorCallback)
  69726. errorCallback();
  69727. }
  69728. else {
  69729. // If the DB hasn't been opened or created yet
  69730. if (!this.db) {
  69731. this.hasReachedQuota = false;
  69732. this.isSupported = true;
  69733. var request = this.idbFactory.open("babylonjs", 1);
  69734. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69735. request.onerror = function (event) {
  69736. handleError();
  69737. };
  69738. // executes when a version change transaction cannot complete due to other active transactions
  69739. request.onblocked = function (event) {
  69740. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69741. handleError();
  69742. };
  69743. // DB has been opened successfully
  69744. request.onsuccess = function (event) {
  69745. _this.db = request.result;
  69746. successCallback();
  69747. };
  69748. // Initialization of the DB. Creating Scenes & Textures stores
  69749. request.onupgradeneeded = function (event) {
  69750. _this.db = (event.target).result;
  69751. if (_this.db) {
  69752. try {
  69753. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69754. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69755. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69756. }
  69757. catch (ex) {
  69758. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69759. handleError();
  69760. }
  69761. }
  69762. };
  69763. }
  69764. // DB has already been created and opened
  69765. else {
  69766. if (successCallback)
  69767. successCallback();
  69768. }
  69769. }
  69770. };
  69771. /**
  69772. * Loads an image from the database
  69773. * @param url defines the url to load from
  69774. * @param image defines the target DOM image
  69775. */
  69776. Database.prototype.loadImageFromDB = function (url, image) {
  69777. var _this = this;
  69778. var completeURL = Database._ReturnFullUrlLocation(url);
  69779. var saveAndLoadImage = function () {
  69780. if (!_this.hasReachedQuota && _this.db !== null) {
  69781. // the texture is not yet in the DB, let's try to save it
  69782. _this._saveImageIntoDBAsync(completeURL, image);
  69783. }
  69784. // If the texture is not in the DB and we've reached the DB quota limit
  69785. // let's load it directly from the web
  69786. else {
  69787. image.src = url;
  69788. }
  69789. };
  69790. if (!this.mustUpdateRessources) {
  69791. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69792. }
  69793. // First time we're download the images or update requested in the manifest file by a version change
  69794. else {
  69795. saveAndLoadImage();
  69796. }
  69797. };
  69798. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69799. if (this.isSupported && this.db !== null) {
  69800. var texture;
  69801. var transaction = this.db.transaction(["textures"]);
  69802. transaction.onabort = function (event) {
  69803. image.src = url;
  69804. };
  69805. transaction.oncomplete = function (event) {
  69806. var blobTextureURL;
  69807. if (texture) {
  69808. var URL = window.URL || window.webkitURL;
  69809. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69810. image.onerror = function () {
  69811. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69812. image.src = url;
  69813. };
  69814. image.src = blobTextureURL;
  69815. }
  69816. else {
  69817. notInDBCallback();
  69818. }
  69819. };
  69820. var getRequest = transaction.objectStore("textures").get(url);
  69821. getRequest.onsuccess = function (event) {
  69822. texture = (event.target).result;
  69823. };
  69824. getRequest.onerror = function (event) {
  69825. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69826. image.src = url;
  69827. };
  69828. }
  69829. else {
  69830. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69831. image.src = url;
  69832. }
  69833. };
  69834. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69835. var _this = this;
  69836. if (this.isSupported) {
  69837. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69838. var generateBlobUrl = function () {
  69839. var blobTextureURL;
  69840. if (blob) {
  69841. var URL = window.URL || window.webkitURL;
  69842. try {
  69843. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69844. }
  69845. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69846. catch (ex) {
  69847. blobTextureURL = URL.createObjectURL(blob);
  69848. }
  69849. }
  69850. if (blobTextureURL) {
  69851. image.src = blobTextureURL;
  69852. }
  69853. };
  69854. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69855. var xhr = new XMLHttpRequest(), blob;
  69856. xhr.open("GET", url, true);
  69857. xhr.responseType = "blob";
  69858. xhr.addEventListener("load", function () {
  69859. if (xhr.status === 200 && _this.db) {
  69860. // Blob as response (XHR2)
  69861. blob = xhr.response;
  69862. var transaction = _this.db.transaction(["textures"], "readwrite");
  69863. // the transaction could abort because of a QuotaExceededError error
  69864. transaction.onabort = function (event) {
  69865. try {
  69866. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69867. var srcElement = (event.srcElement || event.target);
  69868. var error = srcElement.error;
  69869. if (error && error.name === "QuotaExceededError") {
  69870. _this.hasReachedQuota = true;
  69871. }
  69872. }
  69873. catch (ex) { }
  69874. generateBlobUrl();
  69875. };
  69876. transaction.oncomplete = function (event) {
  69877. generateBlobUrl();
  69878. };
  69879. var newTexture = { textureUrl: url, data: blob };
  69880. try {
  69881. // Put the blob into the dabase
  69882. var addRequest = transaction.objectStore("textures").put(newTexture);
  69883. addRequest.onsuccess = function (event) {
  69884. };
  69885. addRequest.onerror = function (event) {
  69886. generateBlobUrl();
  69887. };
  69888. }
  69889. catch (ex) {
  69890. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69891. if (ex.code === 25) {
  69892. Database.IsUASupportingBlobStorage = false;
  69893. }
  69894. image.src = url;
  69895. }
  69896. }
  69897. else {
  69898. image.src = url;
  69899. }
  69900. }, false);
  69901. xhr.addEventListener("error", function (event) {
  69902. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69903. image.src = url;
  69904. }, false);
  69905. xhr.send();
  69906. }
  69907. else {
  69908. image.src = url;
  69909. }
  69910. }
  69911. else {
  69912. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69913. image.src = url;
  69914. }
  69915. };
  69916. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69917. var _this = this;
  69918. var updateVersion = function () {
  69919. // the version is not yet in the DB or we need to update it
  69920. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69921. };
  69922. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69923. };
  69924. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69925. var _this = this;
  69926. if (this.isSupported && this.db) {
  69927. var version;
  69928. try {
  69929. var transaction = this.db.transaction(["versions"]);
  69930. transaction.oncomplete = function (event) {
  69931. if (version) {
  69932. // If the version in the JSON file is different from the version in DB
  69933. if (_this.manifestVersionFound !== version.data) {
  69934. _this.mustUpdateRessources = true;
  69935. updateInDBCallback();
  69936. }
  69937. else {
  69938. callback(version.data);
  69939. }
  69940. }
  69941. // version was not found in DB
  69942. else {
  69943. _this.mustUpdateRessources = true;
  69944. updateInDBCallback();
  69945. }
  69946. };
  69947. transaction.onabort = function (event) {
  69948. callback(-1);
  69949. };
  69950. var getRequest = transaction.objectStore("versions").get(url);
  69951. getRequest.onsuccess = function (event) {
  69952. version = (event.target).result;
  69953. };
  69954. getRequest.onerror = function (event) {
  69955. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69956. callback(-1);
  69957. };
  69958. }
  69959. catch (ex) {
  69960. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69961. callback(-1);
  69962. }
  69963. }
  69964. else {
  69965. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69966. callback(-1);
  69967. }
  69968. };
  69969. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69970. var _this = this;
  69971. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69972. try {
  69973. // Open a transaction to the database
  69974. var transaction = this.db.transaction(["versions"], "readwrite");
  69975. // the transaction could abort because of a QuotaExceededError error
  69976. transaction.onabort = function (event) {
  69977. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69978. var error = event.srcElement['error'];
  69979. if (error && error.name === "QuotaExceededError") {
  69980. _this.hasReachedQuota = true;
  69981. }
  69982. }
  69983. catch (ex) { }
  69984. callback(-1);
  69985. };
  69986. transaction.oncomplete = function (event) {
  69987. callback(_this.manifestVersionFound);
  69988. };
  69989. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69990. // Put the scene into the database
  69991. var addRequest = transaction.objectStore("versions").put(newVersion);
  69992. addRequest.onsuccess = function (event) {
  69993. };
  69994. addRequest.onerror = function (event) {
  69995. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69996. };
  69997. }
  69998. catch (ex) {
  69999. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  70000. callback(-1);
  70001. }
  70002. }
  70003. else {
  70004. callback(-1);
  70005. }
  70006. };
  70007. /**
  70008. * Loads a file from database
  70009. * @param url defines the URL to load from
  70010. * @param sceneLoaded defines a callback to call on success
  70011. * @param progressCallBack defines a callback to call when progress changed
  70012. * @param errorCallback defines a callback to call on error
  70013. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70014. */
  70015. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70016. var _this = this;
  70017. var completeUrl = Database._ReturnFullUrlLocation(url);
  70018. var saveAndLoadFile = function () {
  70019. // the scene is not yet in the DB, let's try to save it
  70020. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  70021. };
  70022. this._checkVersionFromDB(completeUrl, function (version) {
  70023. if (version !== -1) {
  70024. if (!_this.mustUpdateRessources) {
  70025. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70026. }
  70027. else {
  70028. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  70029. }
  70030. }
  70031. else {
  70032. if (errorCallback) {
  70033. errorCallback();
  70034. }
  70035. }
  70036. });
  70037. };
  70038. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70039. if (this.isSupported && this.db) {
  70040. var targetStore;
  70041. if (url.indexOf(".babylon") !== -1) {
  70042. targetStore = "scenes";
  70043. }
  70044. else {
  70045. targetStore = "textures";
  70046. }
  70047. var file;
  70048. var transaction = this.db.transaction([targetStore]);
  70049. transaction.oncomplete = function (event) {
  70050. if (file) {
  70051. callback(file.data);
  70052. }
  70053. // file was not found in DB
  70054. else {
  70055. notInDBCallback();
  70056. }
  70057. };
  70058. transaction.onabort = function (event) {
  70059. notInDBCallback();
  70060. };
  70061. var getRequest = transaction.objectStore(targetStore).get(url);
  70062. getRequest.onsuccess = function (event) {
  70063. file = (event.target).result;
  70064. };
  70065. getRequest.onerror = function (event) {
  70066. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70067. notInDBCallback();
  70068. };
  70069. }
  70070. else {
  70071. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70072. callback();
  70073. }
  70074. };
  70075. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  70076. var _this = this;
  70077. if (this.isSupported) {
  70078. var targetStore;
  70079. if (url.indexOf(".babylon") !== -1) {
  70080. targetStore = "scenes";
  70081. }
  70082. else {
  70083. targetStore = "textures";
  70084. }
  70085. // Create XHR
  70086. var xhr = new XMLHttpRequest();
  70087. var fileData;
  70088. xhr.open("GET", url, true);
  70089. if (useArrayBuffer) {
  70090. xhr.responseType = "arraybuffer";
  70091. }
  70092. if (progressCallback) {
  70093. xhr.onprogress = progressCallback;
  70094. }
  70095. xhr.addEventListener("load", function () {
  70096. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  70097. // Blob as response (XHR2)
  70098. //fileData = xhr.responseText;
  70099. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  70100. if (!_this.hasReachedQuota && _this.db) {
  70101. // Open a transaction to the database
  70102. var transaction = _this.db.transaction([targetStore], "readwrite");
  70103. // the transaction could abort because of a QuotaExceededError error
  70104. transaction.onabort = function (event) {
  70105. try {
  70106. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70107. var error = event.srcElement['error'];
  70108. if (error && error.name === "QuotaExceededError") {
  70109. _this.hasReachedQuota = true;
  70110. }
  70111. }
  70112. catch (ex) { }
  70113. callback(fileData);
  70114. };
  70115. transaction.oncomplete = function (event) {
  70116. callback(fileData);
  70117. };
  70118. var newFile;
  70119. if (targetStore === "scenes") {
  70120. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  70121. }
  70122. else {
  70123. newFile = { textureUrl: url, data: fileData };
  70124. }
  70125. try {
  70126. // Put the scene into the database
  70127. var addRequest = transaction.objectStore(targetStore).put(newFile);
  70128. addRequest.onsuccess = function (event) {
  70129. };
  70130. addRequest.onerror = function (event) {
  70131. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  70132. };
  70133. }
  70134. catch (ex) {
  70135. callback(fileData);
  70136. }
  70137. }
  70138. else {
  70139. callback(fileData);
  70140. }
  70141. }
  70142. else {
  70143. callback();
  70144. }
  70145. }, false);
  70146. xhr.addEventListener("error", function (event) {
  70147. BABYLON.Tools.Error("error on XHR request.");
  70148. callback();
  70149. }, false);
  70150. xhr.send();
  70151. }
  70152. else {
  70153. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70154. callback();
  70155. }
  70156. };
  70157. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70158. Database.IsUASupportingBlobStorage = true;
  70159. /** Gets a boolean indicating if Database storate is enabled */
  70160. Database.IDBStorageEnabled = true;
  70161. Database._ParseURL = function (url) {
  70162. var a = document.createElement('a');
  70163. a.href = url;
  70164. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70165. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70166. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70167. return absLocation;
  70168. };
  70169. Database._ReturnFullUrlLocation = function (url) {
  70170. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70171. return (Database._ParseURL(window.location.href) + url);
  70172. }
  70173. else {
  70174. return url;
  70175. }
  70176. };
  70177. return Database;
  70178. }());
  70179. BABYLON.Database = Database;
  70180. })(BABYLON || (BABYLON = {}));
  70181. //# sourceMappingURL=babylon.database.js.map
  70182. var BABYLON;
  70183. (function (BABYLON) {
  70184. var FresnelParameters = /** @class */ (function () {
  70185. function FresnelParameters() {
  70186. this._isEnabled = true;
  70187. this.leftColor = BABYLON.Color3.White();
  70188. this.rightColor = BABYLON.Color3.Black();
  70189. this.bias = 0;
  70190. this.power = 1;
  70191. }
  70192. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70193. get: function () {
  70194. return this._isEnabled;
  70195. },
  70196. set: function (value) {
  70197. if (this._isEnabled === value) {
  70198. return;
  70199. }
  70200. this._isEnabled = value;
  70201. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70202. },
  70203. enumerable: true,
  70204. configurable: true
  70205. });
  70206. FresnelParameters.prototype.clone = function () {
  70207. var newFresnelParameters = new FresnelParameters();
  70208. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70209. return newFresnelParameters;
  70210. };
  70211. FresnelParameters.prototype.serialize = function () {
  70212. var serializationObject = {};
  70213. serializationObject.isEnabled = this.isEnabled;
  70214. serializationObject.leftColor = this.leftColor.asArray();
  70215. serializationObject.rightColor = this.rightColor.asArray();
  70216. serializationObject.bias = this.bias;
  70217. serializationObject.power = this.power;
  70218. return serializationObject;
  70219. };
  70220. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70221. var fresnelParameters = new FresnelParameters();
  70222. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70223. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70224. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70225. fresnelParameters.bias = parsedFresnelParameters.bias;
  70226. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70227. return fresnelParameters;
  70228. };
  70229. return FresnelParameters;
  70230. }());
  70231. BABYLON.FresnelParameters = FresnelParameters;
  70232. })(BABYLON || (BABYLON = {}));
  70233. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70234. var BABYLON;
  70235. (function (BABYLON) {
  70236. var MultiMaterial = /** @class */ (function (_super) {
  70237. __extends(MultiMaterial, _super);
  70238. function MultiMaterial(name, scene) {
  70239. var _this = _super.call(this, name, scene, true) || this;
  70240. scene.multiMaterials.push(_this);
  70241. _this.subMaterials = new Array();
  70242. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70243. return _this;
  70244. }
  70245. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70246. get: function () {
  70247. return this._subMaterials;
  70248. },
  70249. set: function (value) {
  70250. this._subMaterials = value;
  70251. this._hookArray(value);
  70252. },
  70253. enumerable: true,
  70254. configurable: true
  70255. });
  70256. MultiMaterial.prototype._hookArray = function (array) {
  70257. var _this = this;
  70258. var oldPush = array.push;
  70259. array.push = function () {
  70260. var items = [];
  70261. for (var _i = 0; _i < arguments.length; _i++) {
  70262. items[_i] = arguments[_i];
  70263. }
  70264. var result = oldPush.apply(array, items);
  70265. _this._markAllSubMeshesAsTexturesDirty();
  70266. return result;
  70267. };
  70268. var oldSplice = array.splice;
  70269. array.splice = function (index, deleteCount) {
  70270. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70271. _this._markAllSubMeshesAsTexturesDirty();
  70272. return deleted;
  70273. };
  70274. };
  70275. // Properties
  70276. MultiMaterial.prototype.getSubMaterial = function (index) {
  70277. if (index < 0 || index >= this.subMaterials.length) {
  70278. return this.getScene().defaultMaterial;
  70279. }
  70280. return this.subMaterials[index];
  70281. };
  70282. MultiMaterial.prototype.getActiveTextures = function () {
  70283. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70284. if (subMaterial) {
  70285. return subMaterial.getActiveTextures();
  70286. }
  70287. else {
  70288. return [];
  70289. }
  70290. }));
  70291. var _a;
  70292. };
  70293. // Methods
  70294. MultiMaterial.prototype.getClassName = function () {
  70295. return "MultiMaterial";
  70296. };
  70297. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70298. for (var index = 0; index < this.subMaterials.length; index++) {
  70299. var subMaterial = this.subMaterials[index];
  70300. if (subMaterial) {
  70301. if (subMaterial.storeEffectOnSubMeshes) {
  70302. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70303. return false;
  70304. }
  70305. continue;
  70306. }
  70307. if (!subMaterial.isReady(mesh)) {
  70308. return false;
  70309. }
  70310. }
  70311. }
  70312. return true;
  70313. };
  70314. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70315. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70316. for (var index = 0; index < this.subMaterials.length; index++) {
  70317. var subMaterial = null;
  70318. var current = this.subMaterials[index];
  70319. if (cloneChildren && current) {
  70320. subMaterial = current.clone(name + "-" + current.name);
  70321. }
  70322. else {
  70323. subMaterial = this.subMaterials[index];
  70324. }
  70325. newMultiMaterial.subMaterials.push(subMaterial);
  70326. }
  70327. return newMultiMaterial;
  70328. };
  70329. MultiMaterial.prototype.serialize = function () {
  70330. var serializationObject = {};
  70331. serializationObject.name = this.name;
  70332. serializationObject.id = this.id;
  70333. if (BABYLON.Tags) {
  70334. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70335. }
  70336. serializationObject.materials = [];
  70337. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70338. var subMat = this.subMaterials[matIndex];
  70339. if (subMat) {
  70340. serializationObject.materials.push(subMat.id);
  70341. }
  70342. else {
  70343. serializationObject.materials.push(null);
  70344. }
  70345. }
  70346. return serializationObject;
  70347. };
  70348. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70349. var scene = this.getScene();
  70350. if (!scene) {
  70351. return;
  70352. }
  70353. var index = scene.multiMaterials.indexOf(this);
  70354. if (index >= 0) {
  70355. scene.multiMaterials.splice(index, 1);
  70356. }
  70357. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70358. };
  70359. return MultiMaterial;
  70360. }(BABYLON.Material));
  70361. BABYLON.MultiMaterial = MultiMaterial;
  70362. })(BABYLON || (BABYLON = {}));
  70363. //# sourceMappingURL=babylon.multiMaterial.js.map
  70364. var BABYLON;
  70365. (function (BABYLON) {
  70366. var FreeCameraTouchInput = /** @class */ (function () {
  70367. function FreeCameraTouchInput() {
  70368. this._offsetX = null;
  70369. this._offsetY = null;
  70370. this._pointerPressed = new Array();
  70371. this.touchAngularSensibility = 200000.0;
  70372. this.touchMoveSensibility = 250.0;
  70373. }
  70374. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70375. var _this = this;
  70376. var previousPosition = null;
  70377. if (this._pointerInput === undefined) {
  70378. this._onLostFocus = function (evt) {
  70379. _this._offsetX = null;
  70380. _this._offsetY = null;
  70381. };
  70382. this._pointerInput = function (p, s) {
  70383. var evt = p.event;
  70384. if (evt.pointerType === "mouse") {
  70385. return;
  70386. }
  70387. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70388. if (!noPreventDefault) {
  70389. evt.preventDefault();
  70390. }
  70391. _this._pointerPressed.push(evt.pointerId);
  70392. if (_this._pointerPressed.length !== 1) {
  70393. return;
  70394. }
  70395. previousPosition = {
  70396. x: evt.clientX,
  70397. y: evt.clientY
  70398. };
  70399. }
  70400. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70401. if (!noPreventDefault) {
  70402. evt.preventDefault();
  70403. }
  70404. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70405. if (index === -1) {
  70406. return;
  70407. }
  70408. _this._pointerPressed.splice(index, 1);
  70409. if (index != 0) {
  70410. return;
  70411. }
  70412. previousPosition = null;
  70413. _this._offsetX = null;
  70414. _this._offsetY = null;
  70415. }
  70416. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70417. if (!noPreventDefault) {
  70418. evt.preventDefault();
  70419. }
  70420. if (!previousPosition) {
  70421. return;
  70422. }
  70423. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70424. if (index != 0) {
  70425. return;
  70426. }
  70427. _this._offsetX = evt.clientX - previousPosition.x;
  70428. _this._offsetY = -(evt.clientY - previousPosition.y);
  70429. }
  70430. };
  70431. }
  70432. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70433. if (this._onLostFocus) {
  70434. element.addEventListener("blur", this._onLostFocus);
  70435. }
  70436. };
  70437. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70438. if (this._pointerInput && element) {
  70439. if (this._observer) {
  70440. this.camera.getScene().onPointerObservable.remove(this._observer);
  70441. this._observer = null;
  70442. }
  70443. if (this._onLostFocus) {
  70444. element.removeEventListener("blur", this._onLostFocus);
  70445. this._onLostFocus = null;
  70446. }
  70447. this._pointerPressed = [];
  70448. this._offsetX = null;
  70449. this._offsetY = null;
  70450. }
  70451. };
  70452. FreeCameraTouchInput.prototype.checkInputs = function () {
  70453. if (this._offsetX && this._offsetY) {
  70454. var camera = this.camera;
  70455. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70456. if (this._pointerPressed.length > 1) {
  70457. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70458. }
  70459. else {
  70460. var speed = camera._computeLocalCameraSpeed();
  70461. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70462. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70463. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70464. }
  70465. }
  70466. };
  70467. FreeCameraTouchInput.prototype.getClassName = function () {
  70468. return "FreeCameraTouchInput";
  70469. };
  70470. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70471. return "touch";
  70472. };
  70473. __decorate([
  70474. BABYLON.serialize()
  70475. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70476. __decorate([
  70477. BABYLON.serialize()
  70478. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70479. return FreeCameraTouchInput;
  70480. }());
  70481. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70482. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70483. })(BABYLON || (BABYLON = {}));
  70484. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70485. var BABYLON;
  70486. (function (BABYLON) {
  70487. // We're mainly based on the logic defined into the FreeCamera code
  70488. var TouchCamera = /** @class */ (function (_super) {
  70489. __extends(TouchCamera, _super);
  70490. //-- end properties for backward compatibility for inputs
  70491. function TouchCamera(name, position, scene) {
  70492. var _this = _super.call(this, name, position, scene) || this;
  70493. _this.inputs.addTouch();
  70494. _this._setupInputs();
  70495. return _this;
  70496. }
  70497. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70498. //-- Begin properties for backward compatibility for inputs
  70499. get: function () {
  70500. var touch = this.inputs.attached["touch"];
  70501. if (touch)
  70502. return touch.touchAngularSensibility;
  70503. return 0;
  70504. },
  70505. set: function (value) {
  70506. var touch = this.inputs.attached["touch"];
  70507. if (touch)
  70508. touch.touchAngularSensibility = value;
  70509. },
  70510. enumerable: true,
  70511. configurable: true
  70512. });
  70513. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70514. get: function () {
  70515. var touch = this.inputs.attached["touch"];
  70516. if (touch)
  70517. return touch.touchMoveSensibility;
  70518. return 0;
  70519. },
  70520. set: function (value) {
  70521. var touch = this.inputs.attached["touch"];
  70522. if (touch)
  70523. touch.touchMoveSensibility = value;
  70524. },
  70525. enumerable: true,
  70526. configurable: true
  70527. });
  70528. TouchCamera.prototype.getClassName = function () {
  70529. return "TouchCamera";
  70530. };
  70531. TouchCamera.prototype._setupInputs = function () {
  70532. var mouse = this.inputs.attached["mouse"];
  70533. if (mouse) {
  70534. mouse.touchEnabled = false;
  70535. }
  70536. };
  70537. return TouchCamera;
  70538. }(BABYLON.FreeCamera));
  70539. BABYLON.TouchCamera = TouchCamera;
  70540. })(BABYLON || (BABYLON = {}));
  70541. //# sourceMappingURL=babylon.touchCamera.js.map
  70542. var BABYLON;
  70543. (function (BABYLON) {
  70544. var ProceduralTexture = /** @class */ (function (_super) {
  70545. __extends(ProceduralTexture, _super);
  70546. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70547. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70548. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70549. if (isCube === void 0) { isCube = false; }
  70550. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70551. _this.isCube = isCube;
  70552. _this.isEnabled = true;
  70553. _this._currentRefreshId = -1;
  70554. _this._refreshRate = 1;
  70555. _this._vertexBuffers = {};
  70556. _this._uniforms = new Array();
  70557. _this._samplers = new Array();
  70558. _this._textures = {};
  70559. _this._floats = {};
  70560. _this._floatsArrays = {};
  70561. _this._colors3 = {};
  70562. _this._colors4 = {};
  70563. _this._vectors2 = {};
  70564. _this._vectors3 = {};
  70565. _this._matrices = {};
  70566. _this._fallbackTextureUsed = false;
  70567. scene.proceduralTextures.push(_this);
  70568. _this._engine = scene.getEngine();
  70569. _this.name = name;
  70570. _this.isRenderTarget = true;
  70571. _this._size = size;
  70572. _this._generateMipMaps = generateMipMaps;
  70573. _this.setFragment(fragment);
  70574. _this._fallbackTexture = fallbackTexture;
  70575. if (isCube) {
  70576. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70577. _this.setFloat("face", 0);
  70578. }
  70579. else {
  70580. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70581. }
  70582. // VBO
  70583. var vertices = [];
  70584. vertices.push(1, 1);
  70585. vertices.push(-1, 1);
  70586. vertices.push(-1, -1);
  70587. vertices.push(1, -1);
  70588. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70589. _this._createIndexBuffer();
  70590. return _this;
  70591. }
  70592. ProceduralTexture.prototype._createIndexBuffer = function () {
  70593. var engine = this._engine;
  70594. // Indices
  70595. var indices = [];
  70596. indices.push(0);
  70597. indices.push(1);
  70598. indices.push(2);
  70599. indices.push(0);
  70600. indices.push(2);
  70601. indices.push(3);
  70602. this._indexBuffer = engine.createIndexBuffer(indices);
  70603. };
  70604. ProceduralTexture.prototype._rebuild = function () {
  70605. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70606. if (vb) {
  70607. vb._rebuild();
  70608. }
  70609. this._createIndexBuffer();
  70610. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70611. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70612. }
  70613. };
  70614. ProceduralTexture.prototype.reset = function () {
  70615. if (this._effect === undefined) {
  70616. return;
  70617. }
  70618. var engine = this._engine;
  70619. engine._releaseEffect(this._effect);
  70620. };
  70621. ProceduralTexture.prototype.isReady = function () {
  70622. var _this = this;
  70623. var engine = this._engine;
  70624. var shaders;
  70625. if (!this._fragment) {
  70626. return false;
  70627. }
  70628. if (this._fallbackTextureUsed) {
  70629. return true;
  70630. }
  70631. if (this._fragment.fragmentElement !== undefined) {
  70632. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70633. }
  70634. else {
  70635. shaders = { vertex: "procedural", fragment: this._fragment };
  70636. }
  70637. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70638. _this.releaseInternalTexture();
  70639. if (_this._fallbackTexture) {
  70640. _this._texture = _this._fallbackTexture._texture;
  70641. if (_this._texture) {
  70642. _this._texture.incrementReferences();
  70643. }
  70644. }
  70645. _this._fallbackTextureUsed = true;
  70646. });
  70647. return this._effect.isReady();
  70648. };
  70649. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70650. this._currentRefreshId = -1;
  70651. };
  70652. ProceduralTexture.prototype.setFragment = function (fragment) {
  70653. this._fragment = fragment;
  70654. };
  70655. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70656. get: function () {
  70657. return this._refreshRate;
  70658. },
  70659. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70660. set: function (value) {
  70661. this._refreshRate = value;
  70662. this.resetRefreshCounter();
  70663. },
  70664. enumerable: true,
  70665. configurable: true
  70666. });
  70667. ProceduralTexture.prototype._shouldRender = function () {
  70668. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70669. return false;
  70670. }
  70671. if (this._fallbackTextureUsed) {
  70672. return false;
  70673. }
  70674. if (this._currentRefreshId === -1) { // At least render once
  70675. this._currentRefreshId = 1;
  70676. return true;
  70677. }
  70678. if (this.refreshRate === this._currentRefreshId) {
  70679. this._currentRefreshId = 1;
  70680. return true;
  70681. }
  70682. this._currentRefreshId++;
  70683. return false;
  70684. };
  70685. ProceduralTexture.prototype.getRenderSize = function () {
  70686. return this._size;
  70687. };
  70688. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70689. if (this._fallbackTextureUsed) {
  70690. return;
  70691. }
  70692. this.releaseInternalTexture();
  70693. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70694. // Update properties
  70695. this._size = size;
  70696. this._generateMipMaps = generateMipMaps;
  70697. };
  70698. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70699. if (this._uniforms.indexOf(uniformName) === -1) {
  70700. this._uniforms.push(uniformName);
  70701. }
  70702. };
  70703. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70704. if (this._samplers.indexOf(name) === -1) {
  70705. this._samplers.push(name);
  70706. }
  70707. this._textures[name] = texture;
  70708. return this;
  70709. };
  70710. ProceduralTexture.prototype.setFloat = function (name, value) {
  70711. this._checkUniform(name);
  70712. this._floats[name] = value;
  70713. return this;
  70714. };
  70715. ProceduralTexture.prototype.setFloats = function (name, value) {
  70716. this._checkUniform(name);
  70717. this._floatsArrays[name] = value;
  70718. return this;
  70719. };
  70720. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70721. this._checkUniform(name);
  70722. this._colors3[name] = value;
  70723. return this;
  70724. };
  70725. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70726. this._checkUniform(name);
  70727. this._colors4[name] = value;
  70728. return this;
  70729. };
  70730. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70731. this._checkUniform(name);
  70732. this._vectors2[name] = value;
  70733. return this;
  70734. };
  70735. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70736. this._checkUniform(name);
  70737. this._vectors3[name] = value;
  70738. return this;
  70739. };
  70740. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70741. this._checkUniform(name);
  70742. this._matrices[name] = value;
  70743. return this;
  70744. };
  70745. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70746. var scene = this.getScene();
  70747. if (!scene) {
  70748. return;
  70749. }
  70750. var engine = this._engine;
  70751. // Render
  70752. engine.enableEffect(this._effect);
  70753. engine.setState(false);
  70754. // Texture
  70755. for (var name in this._textures) {
  70756. this._effect.setTexture(name, this._textures[name]);
  70757. }
  70758. // Float
  70759. for (name in this._floats) {
  70760. this._effect.setFloat(name, this._floats[name]);
  70761. }
  70762. // Floats
  70763. for (name in this._floatsArrays) {
  70764. this._effect.setArray(name, this._floatsArrays[name]);
  70765. }
  70766. // Color3
  70767. for (name in this._colors3) {
  70768. this._effect.setColor3(name, this._colors3[name]);
  70769. }
  70770. // Color4
  70771. for (name in this._colors4) {
  70772. var color = this._colors4[name];
  70773. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70774. }
  70775. // Vector2
  70776. for (name in this._vectors2) {
  70777. this._effect.setVector2(name, this._vectors2[name]);
  70778. }
  70779. // Vector3
  70780. for (name in this._vectors3) {
  70781. this._effect.setVector3(name, this._vectors3[name]);
  70782. }
  70783. // Matrix
  70784. for (name in this._matrices) {
  70785. this._effect.setMatrix(name, this._matrices[name]);
  70786. }
  70787. if (!this._texture) {
  70788. return;
  70789. }
  70790. if (this.isCube) {
  70791. for (var face = 0; face < 6; face++) {
  70792. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70793. // VBOs
  70794. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70795. this._effect.setFloat("face", face);
  70796. // Clear
  70797. engine.clear(scene.clearColor, true, true, true);
  70798. // Draw order
  70799. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70800. // Mipmaps
  70801. if (face === 5) {
  70802. engine.generateMipMapsForCubemap(this._texture);
  70803. }
  70804. }
  70805. }
  70806. else {
  70807. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70808. // VBOs
  70809. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70810. // Clear
  70811. engine.clear(scene.clearColor, true, true, true);
  70812. // Draw order
  70813. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70814. }
  70815. // Unbind
  70816. engine.unBindFramebuffer(this._texture, this.isCube);
  70817. if (this.onGenerated) {
  70818. this.onGenerated();
  70819. }
  70820. };
  70821. ProceduralTexture.prototype.clone = function () {
  70822. var textureSize = this.getSize();
  70823. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70824. // Base texture
  70825. newTexture.hasAlpha = this.hasAlpha;
  70826. newTexture.level = this.level;
  70827. // RenderTarget Texture
  70828. newTexture.coordinatesMode = this.coordinatesMode;
  70829. return newTexture;
  70830. };
  70831. ProceduralTexture.prototype.dispose = function () {
  70832. var scene = this.getScene();
  70833. if (!scene) {
  70834. return;
  70835. }
  70836. var index = scene.proceduralTextures.indexOf(this);
  70837. if (index >= 0) {
  70838. scene.proceduralTextures.splice(index, 1);
  70839. }
  70840. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70841. if (vertexBuffer) {
  70842. vertexBuffer.dispose();
  70843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70844. }
  70845. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70846. this._indexBuffer = null;
  70847. }
  70848. _super.prototype.dispose.call(this);
  70849. };
  70850. __decorate([
  70851. BABYLON.serialize()
  70852. ], ProceduralTexture.prototype, "_size", void 0);
  70853. __decorate([
  70854. BABYLON.serialize()
  70855. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70856. __decorate([
  70857. BABYLON.serialize()
  70858. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70859. __decorate([
  70860. BABYLON.serialize()
  70861. ], ProceduralTexture.prototype, "refreshRate", null);
  70862. return ProceduralTexture;
  70863. }(BABYLON.Texture));
  70864. BABYLON.ProceduralTexture = ProceduralTexture;
  70865. })(BABYLON || (BABYLON = {}));
  70866. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70867. var BABYLON;
  70868. (function (BABYLON) {
  70869. var CustomProceduralTexture = /** @class */ (function (_super) {
  70870. __extends(CustomProceduralTexture, _super);
  70871. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70872. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70873. _this._animate = true;
  70874. _this._time = 0;
  70875. _this._texturePath = texturePath;
  70876. //Try to load json
  70877. _this.loadJson(texturePath);
  70878. _this.refreshRate = 1;
  70879. return _this;
  70880. }
  70881. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70882. var _this = this;
  70883. var noConfigFile = function () {
  70884. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70885. try {
  70886. _this.setFragment(_this._texturePath);
  70887. }
  70888. catch (ex) {
  70889. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70890. }
  70891. };
  70892. var configFileUrl = jsonUrl + "/config.json";
  70893. var xhr = new XMLHttpRequest();
  70894. xhr.open("GET", configFileUrl, true);
  70895. xhr.addEventListener("load", function () {
  70896. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70897. try {
  70898. _this._config = JSON.parse(xhr.response);
  70899. _this.updateShaderUniforms();
  70900. _this.updateTextures();
  70901. _this.setFragment(_this._texturePath + "/custom");
  70902. _this._animate = _this._config.animate;
  70903. _this.refreshRate = _this._config.refreshrate;
  70904. }
  70905. catch (ex) {
  70906. noConfigFile();
  70907. }
  70908. }
  70909. else {
  70910. noConfigFile();
  70911. }
  70912. }, false);
  70913. xhr.addEventListener("error", function () {
  70914. noConfigFile();
  70915. }, false);
  70916. try {
  70917. xhr.send();
  70918. }
  70919. catch (ex) {
  70920. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70921. }
  70922. };
  70923. CustomProceduralTexture.prototype.isReady = function () {
  70924. if (!_super.prototype.isReady.call(this)) {
  70925. return false;
  70926. }
  70927. for (var name in this._textures) {
  70928. var texture = this._textures[name];
  70929. if (!texture.isReady()) {
  70930. return false;
  70931. }
  70932. }
  70933. return true;
  70934. };
  70935. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70936. var scene = this.getScene();
  70937. if (this._animate && scene) {
  70938. this._time += scene.getAnimationRatio() * 0.03;
  70939. this.updateShaderUniforms();
  70940. }
  70941. _super.prototype.render.call(this, useCameraPostProcess);
  70942. };
  70943. CustomProceduralTexture.prototype.updateTextures = function () {
  70944. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70945. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70946. }
  70947. };
  70948. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70949. if (this._config) {
  70950. for (var j = 0; j < this._config.uniforms.length; j++) {
  70951. var uniform = this._config.uniforms[j];
  70952. switch (uniform.type) {
  70953. case "float":
  70954. this.setFloat(uniform.name, uniform.value);
  70955. break;
  70956. case "color3":
  70957. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70958. break;
  70959. case "color4":
  70960. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70961. break;
  70962. case "vector2":
  70963. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70964. break;
  70965. case "vector3":
  70966. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70967. break;
  70968. }
  70969. }
  70970. }
  70971. this.setFloat("time", this._time);
  70972. };
  70973. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70974. get: function () {
  70975. return this._animate;
  70976. },
  70977. set: function (value) {
  70978. this._animate = value;
  70979. },
  70980. enumerable: true,
  70981. configurable: true
  70982. });
  70983. return CustomProceduralTexture;
  70984. }(BABYLON.ProceduralTexture));
  70985. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70986. })(BABYLON || (BABYLON = {}));
  70987. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70988. var BABYLON;
  70989. (function (BABYLON) {
  70990. var FreeCameraGamepadInput = /** @class */ (function () {
  70991. function FreeCameraGamepadInput() {
  70992. this.gamepadAngularSensibility = 200;
  70993. this.gamepadMoveSensibility = 40;
  70994. // private members
  70995. this._cameraTransform = BABYLON.Matrix.Identity();
  70996. this._deltaTransform = BABYLON.Vector3.Zero();
  70997. this._vector3 = BABYLON.Vector3.Zero();
  70998. this._vector2 = BABYLON.Vector2.Zero();
  70999. }
  71000. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71001. var _this = this;
  71002. var manager = this.camera.getScene().gamepadManager;
  71003. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71004. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71005. // prioritize XBOX gamepads.
  71006. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71007. _this.gamepad = gamepad;
  71008. }
  71009. }
  71010. });
  71011. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71012. if (_this.gamepad === gamepad) {
  71013. _this.gamepad = null;
  71014. }
  71015. });
  71016. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71017. };
  71018. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71019. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71020. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71021. this.gamepad = null;
  71022. };
  71023. FreeCameraGamepadInput.prototype.checkInputs = function () {
  71024. if (this.gamepad && this.gamepad.leftStick) {
  71025. var camera = this.camera;
  71026. var LSValues = this.gamepad.leftStick;
  71027. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  71028. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71029. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  71030. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  71031. var RSValues = this.gamepad.rightStick;
  71032. if (RSValues) {
  71033. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  71034. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  71035. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  71036. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  71037. }
  71038. else {
  71039. RSValues = { x: 0, y: 0 };
  71040. }
  71041. if (!camera.rotationQuaternion) {
  71042. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  71043. }
  71044. else {
  71045. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  71046. }
  71047. var speed = camera._computeLocalCameraSpeed() * 50.0;
  71048. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  71049. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  71050. camera.cameraDirection.addInPlace(this._deltaTransform);
  71051. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  71052. camera.cameraRotation.addInPlace(this._vector2);
  71053. }
  71054. };
  71055. FreeCameraGamepadInput.prototype.getClassName = function () {
  71056. return "FreeCameraGamepadInput";
  71057. };
  71058. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  71059. return "gamepad";
  71060. };
  71061. __decorate([
  71062. BABYLON.serialize()
  71063. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  71064. __decorate([
  71065. BABYLON.serialize()
  71066. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71067. return FreeCameraGamepadInput;
  71068. }());
  71069. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  71070. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  71071. })(BABYLON || (BABYLON = {}));
  71072. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  71073. var BABYLON;
  71074. (function (BABYLON) {
  71075. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  71076. function ArcRotateCameraGamepadInput() {
  71077. this.gamepadRotationSensibility = 80;
  71078. this.gamepadMoveSensibility = 40;
  71079. }
  71080. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71081. var _this = this;
  71082. var manager = this.camera.getScene().gamepadManager;
  71083. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71084. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71085. // prioritize XBOX gamepads.
  71086. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71087. _this.gamepad = gamepad;
  71088. }
  71089. }
  71090. });
  71091. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71092. if (_this.gamepad === gamepad) {
  71093. _this.gamepad = null;
  71094. }
  71095. });
  71096. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71097. };
  71098. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  71099. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71100. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71101. this.gamepad = null;
  71102. };
  71103. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  71104. if (this.gamepad) {
  71105. var camera = this.camera;
  71106. var RSValues = this.gamepad.rightStick;
  71107. if (RSValues) {
  71108. if (RSValues.x != 0) {
  71109. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  71110. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  71111. camera.inertialAlphaOffset += normalizedRX;
  71112. }
  71113. }
  71114. if (RSValues.y != 0) {
  71115. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  71116. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  71117. camera.inertialBetaOffset += normalizedRY;
  71118. }
  71119. }
  71120. }
  71121. var LSValues = this.gamepad.leftStick;
  71122. if (LSValues && LSValues.y != 0) {
  71123. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71124. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  71125. this.camera.inertialRadiusOffset -= normalizedLY;
  71126. }
  71127. }
  71128. }
  71129. };
  71130. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  71131. return "ArcRotateCameraGamepadInput";
  71132. };
  71133. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  71134. return "gamepad";
  71135. };
  71136. __decorate([
  71137. BABYLON.serialize()
  71138. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  71139. __decorate([
  71140. BABYLON.serialize()
  71141. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71142. return ArcRotateCameraGamepadInput;
  71143. }());
  71144. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  71145. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  71146. })(BABYLON || (BABYLON = {}));
  71147. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  71148. var BABYLON;
  71149. (function (BABYLON) {
  71150. var GamepadManager = /** @class */ (function () {
  71151. function GamepadManager(_scene) {
  71152. var _this = this;
  71153. this._scene = _scene;
  71154. this._babylonGamepads = [];
  71155. this._oneGamepadConnected = false;
  71156. this._isMonitoring = false;
  71157. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71158. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71159. this._gamepadEventSupported = false;
  71160. }
  71161. else {
  71162. this._gamepadEventSupported = 'GamepadEvent' in window;
  71163. this._gamepadSupport = (navigator.getGamepads ||
  71164. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71165. }
  71166. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71167. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71168. for (var i in _this._babylonGamepads) {
  71169. var gamepad = _this._babylonGamepads[i];
  71170. if (gamepad && gamepad._isConnected) {
  71171. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71172. }
  71173. }
  71174. });
  71175. this._onGamepadConnectedEvent = function (evt) {
  71176. var gamepad = evt.gamepad;
  71177. if (gamepad.index in _this._babylonGamepads) {
  71178. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71179. return;
  71180. }
  71181. }
  71182. var newGamepad;
  71183. if (_this._babylonGamepads[gamepad.index]) {
  71184. newGamepad = _this._babylonGamepads[gamepad.index];
  71185. newGamepad.browserGamepad = gamepad;
  71186. newGamepad._isConnected = true;
  71187. }
  71188. else {
  71189. newGamepad = _this._addNewGamepad(gamepad);
  71190. }
  71191. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71192. _this._startMonitoringGamepads();
  71193. };
  71194. this._onGamepadDisconnectedEvent = function (evt) {
  71195. var gamepad = evt.gamepad;
  71196. // Remove the gamepad from the list of gamepads to monitor.
  71197. for (var i in _this._babylonGamepads) {
  71198. if (_this._babylonGamepads[i].index === gamepad.index) {
  71199. var disconnectedGamepad = _this._babylonGamepads[i];
  71200. disconnectedGamepad._isConnected = false;
  71201. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71202. break;
  71203. }
  71204. }
  71205. };
  71206. if (this._gamepadSupport) {
  71207. //first add already-connected gamepads
  71208. this._updateGamepadObjects();
  71209. if (this._babylonGamepads.length) {
  71210. this._startMonitoringGamepads();
  71211. }
  71212. // Checking if the gamepad connected event is supported (like in Firefox)
  71213. if (this._gamepadEventSupported) {
  71214. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71215. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71216. }
  71217. else {
  71218. this._startMonitoringGamepads();
  71219. }
  71220. }
  71221. }
  71222. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71223. get: function () {
  71224. return this._babylonGamepads;
  71225. },
  71226. enumerable: true,
  71227. configurable: true
  71228. });
  71229. GamepadManager.prototype.getGamepadByType = function (type) {
  71230. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71231. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71232. var gamepad = _a[_i];
  71233. if (gamepad && gamepad.type === type) {
  71234. return gamepad;
  71235. }
  71236. }
  71237. return null;
  71238. };
  71239. GamepadManager.prototype.dispose = function () {
  71240. if (this._gamepadEventSupported) {
  71241. if (this._onGamepadConnectedEvent) {
  71242. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71243. }
  71244. if (this._onGamepadDisconnectedEvent) {
  71245. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71246. }
  71247. this._onGamepadConnectedEvent = null;
  71248. this._onGamepadDisconnectedEvent = null;
  71249. }
  71250. this._babylonGamepads.forEach(function (gamepad) {
  71251. gamepad.dispose();
  71252. });
  71253. this.onGamepadConnectedObservable.clear();
  71254. this.onGamepadDisconnectedObservable.clear();
  71255. this._oneGamepadConnected = false;
  71256. this._stopMonitoringGamepads();
  71257. this._babylonGamepads = [];
  71258. };
  71259. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71260. if (!this._oneGamepadConnected) {
  71261. this._oneGamepadConnected = true;
  71262. }
  71263. var newGamepad;
  71264. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71265. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71266. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71267. }
  71268. // if pose is supported, use the (WebVR) pose enabled controller
  71269. else if (gamepad.pose) {
  71270. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71271. }
  71272. else {
  71273. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71274. }
  71275. this._babylonGamepads[newGamepad.index] = newGamepad;
  71276. return newGamepad;
  71277. };
  71278. GamepadManager.prototype._startMonitoringGamepads = function () {
  71279. if (!this._isMonitoring) {
  71280. this._isMonitoring = true;
  71281. //back-comp
  71282. if (!this._scene) {
  71283. this._checkGamepadsStatus();
  71284. }
  71285. }
  71286. };
  71287. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71288. this._isMonitoring = false;
  71289. };
  71290. GamepadManager.prototype._checkGamepadsStatus = function () {
  71291. var _this = this;
  71292. // Hack to be compatible Chrome
  71293. this._updateGamepadObjects();
  71294. for (var i in this._babylonGamepads) {
  71295. var gamepad = this._babylonGamepads[i];
  71296. if (!gamepad || !gamepad.isConnected) {
  71297. continue;
  71298. }
  71299. gamepad.update();
  71300. }
  71301. if (this._isMonitoring && !this._scene) {
  71302. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71303. }
  71304. };
  71305. // This function is called only on Chrome, which does not properly support
  71306. // connection/disconnection events and forces you to recopy again the gamepad object
  71307. GamepadManager.prototype._updateGamepadObjects = function () {
  71308. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71309. for (var i = 0; i < gamepads.length; i++) {
  71310. var gamepad = gamepads[i];
  71311. if (gamepad) {
  71312. if (!this._babylonGamepads[gamepad.index]) {
  71313. var newGamepad = this._addNewGamepad(gamepad);
  71314. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71315. }
  71316. else {
  71317. // Forced to copy again this object for Chrome for unknown reason
  71318. this._babylonGamepads[i].browserGamepad = gamepad;
  71319. if (!this._babylonGamepads[i].isConnected) {
  71320. this._babylonGamepads[i]._isConnected = true;
  71321. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71322. }
  71323. }
  71324. }
  71325. }
  71326. };
  71327. return GamepadManager;
  71328. }());
  71329. BABYLON.GamepadManager = GamepadManager;
  71330. })(BABYLON || (BABYLON = {}));
  71331. //# sourceMappingURL=babylon.gamepadManager.js.map
  71332. var BABYLON;
  71333. (function (BABYLON) {
  71334. var StickValues = /** @class */ (function () {
  71335. function StickValues(x, y) {
  71336. this.x = x;
  71337. this.y = y;
  71338. }
  71339. return StickValues;
  71340. }());
  71341. BABYLON.StickValues = StickValues;
  71342. var Gamepad = /** @class */ (function () {
  71343. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71344. if (leftStickX === void 0) { leftStickX = 0; }
  71345. if (leftStickY === void 0) { leftStickY = 1; }
  71346. if (rightStickX === void 0) { rightStickX = 2; }
  71347. if (rightStickY === void 0) { rightStickY = 3; }
  71348. this.id = id;
  71349. this.index = index;
  71350. this.browserGamepad = browserGamepad;
  71351. this._isConnected = true;
  71352. this._invertLeftStickY = false;
  71353. this.type = Gamepad.GAMEPAD;
  71354. this._leftStickAxisX = leftStickX;
  71355. this._leftStickAxisY = leftStickY;
  71356. this._rightStickAxisX = rightStickX;
  71357. this._rightStickAxisY = rightStickY;
  71358. if (this.browserGamepad.axes.length >= 2) {
  71359. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71360. }
  71361. if (this.browserGamepad.axes.length >= 4) {
  71362. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71363. }
  71364. }
  71365. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71366. get: function () {
  71367. return this._isConnected;
  71368. },
  71369. enumerable: true,
  71370. configurable: true
  71371. });
  71372. Gamepad.prototype.onleftstickchanged = function (callback) {
  71373. this._onleftstickchanged = callback;
  71374. };
  71375. Gamepad.prototype.onrightstickchanged = function (callback) {
  71376. this._onrightstickchanged = callback;
  71377. };
  71378. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71379. get: function () {
  71380. return this._leftStick;
  71381. },
  71382. set: function (newValues) {
  71383. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71384. this._onleftstickchanged(newValues);
  71385. }
  71386. this._leftStick = newValues;
  71387. },
  71388. enumerable: true,
  71389. configurable: true
  71390. });
  71391. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71392. get: function () {
  71393. return this._rightStick;
  71394. },
  71395. set: function (newValues) {
  71396. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71397. this._onrightstickchanged(newValues);
  71398. }
  71399. this._rightStick = newValues;
  71400. },
  71401. enumerable: true,
  71402. configurable: true
  71403. });
  71404. Gamepad.prototype.update = function () {
  71405. if (this._leftStick) {
  71406. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71407. if (this._invertLeftStickY) {
  71408. this.leftStick.y *= -1;
  71409. }
  71410. }
  71411. if (this._rightStick) {
  71412. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71413. }
  71414. };
  71415. Gamepad.prototype.dispose = function () {
  71416. };
  71417. Gamepad.GAMEPAD = 0;
  71418. Gamepad.GENERIC = 1;
  71419. Gamepad.XBOX = 2;
  71420. Gamepad.POSE_ENABLED = 3;
  71421. return Gamepad;
  71422. }());
  71423. BABYLON.Gamepad = Gamepad;
  71424. var GenericPad = /** @class */ (function (_super) {
  71425. __extends(GenericPad, _super);
  71426. function GenericPad(id, index, browserGamepad) {
  71427. var _this = _super.call(this, id, index, browserGamepad) || this;
  71428. _this.onButtonDownObservable = new BABYLON.Observable();
  71429. _this.onButtonUpObservable = new BABYLON.Observable();
  71430. _this.type = Gamepad.GENERIC;
  71431. _this._buttons = new Array(browserGamepad.buttons.length);
  71432. return _this;
  71433. }
  71434. GenericPad.prototype.onbuttondown = function (callback) {
  71435. this._onbuttondown = callback;
  71436. };
  71437. GenericPad.prototype.onbuttonup = function (callback) {
  71438. this._onbuttonup = callback;
  71439. };
  71440. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71441. if (newValue !== currentValue) {
  71442. if (newValue === 1) {
  71443. if (this._onbuttondown) {
  71444. this._onbuttondown(buttonIndex);
  71445. }
  71446. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71447. }
  71448. if (newValue === 0) {
  71449. if (this._onbuttonup) {
  71450. this._onbuttonup(buttonIndex);
  71451. }
  71452. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71453. }
  71454. }
  71455. return newValue;
  71456. };
  71457. GenericPad.prototype.update = function () {
  71458. _super.prototype.update.call(this);
  71459. for (var index = 0; index < this._buttons.length; index++) {
  71460. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71461. }
  71462. };
  71463. GenericPad.prototype.dispose = function () {
  71464. _super.prototype.dispose.call(this);
  71465. this.onButtonDownObservable.clear();
  71466. this.onButtonUpObservable.clear();
  71467. };
  71468. return GenericPad;
  71469. }(Gamepad));
  71470. BABYLON.GenericPad = GenericPad;
  71471. })(BABYLON || (BABYLON = {}));
  71472. //# sourceMappingURL=babylon.gamepad.js.map
  71473. var BABYLON;
  71474. (function (BABYLON) {
  71475. /**
  71476. * Defines supported buttons for XBox360 compatible gamepads
  71477. */
  71478. var Xbox360Button;
  71479. (function (Xbox360Button) {
  71480. /** A */
  71481. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71482. /** B */
  71483. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71484. /** X */
  71485. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71486. /** Y */
  71487. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71488. /** Start */
  71489. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71490. /** Back */
  71491. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71492. /** Left button */
  71493. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71494. /** Right button */
  71495. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71496. /** Left stick */
  71497. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71498. /** Right stick */
  71499. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71500. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71501. /** Defines values for XBox360 DPad */
  71502. var Xbox360Dpad;
  71503. (function (Xbox360Dpad) {
  71504. /** Up */
  71505. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71506. /** Down */
  71507. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71508. /** Left */
  71509. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71510. /** Right */
  71511. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71512. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71513. /**
  71514. * Defines a XBox360 gamepad
  71515. */
  71516. var Xbox360Pad = /** @class */ (function (_super) {
  71517. __extends(Xbox360Pad, _super);
  71518. /**
  71519. * Creates a new XBox360 gamepad object
  71520. * @param id defines the id of this gamepad
  71521. * @param index defines its index
  71522. * @param gamepad defines the internal HTML gamepad object
  71523. * @param xboxOne defines if it is a XBox One gamepad
  71524. */
  71525. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71526. if (xboxOne === void 0) { xboxOne = false; }
  71527. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71528. _this._leftTrigger = 0;
  71529. _this._rightTrigger = 0;
  71530. /** Observable raised when a button is pressed */
  71531. _this.onButtonDownObservable = new BABYLON.Observable();
  71532. /** Observable raised when a button is released */
  71533. _this.onButtonUpObservable = new BABYLON.Observable();
  71534. /** Observable raised when a pad is pressed */
  71535. _this.onPadDownObservable = new BABYLON.Observable();
  71536. /** Observable raised when a pad is released */
  71537. _this.onPadUpObservable = new BABYLON.Observable();
  71538. _this._buttonA = 0;
  71539. _this._buttonB = 0;
  71540. _this._buttonX = 0;
  71541. _this._buttonY = 0;
  71542. _this._buttonBack = 0;
  71543. _this._buttonStart = 0;
  71544. _this._buttonLB = 0;
  71545. _this._buttonRB = 0;
  71546. _this._buttonLeftStick = 0;
  71547. _this._buttonRightStick = 0;
  71548. _this._dPadUp = 0;
  71549. _this._dPadDown = 0;
  71550. _this._dPadLeft = 0;
  71551. _this._dPadRight = 0;
  71552. _this._isXboxOnePad = false;
  71553. _this.type = BABYLON.Gamepad.XBOX;
  71554. _this._isXboxOnePad = xboxOne;
  71555. return _this;
  71556. }
  71557. /**
  71558. * Defines the callback to call when left trigger is pressed
  71559. * @param callback defines the callback to use
  71560. */
  71561. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71562. this._onlefttriggerchanged = callback;
  71563. };
  71564. /**
  71565. * Defines the callback to call when right trigger is pressed
  71566. * @param callback defines the callback to use
  71567. */
  71568. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71569. this._onrighttriggerchanged = callback;
  71570. };
  71571. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71572. /**
  71573. * Gets or sets left trigger value
  71574. */
  71575. get: function () {
  71576. return this._leftTrigger;
  71577. },
  71578. set: function (newValue) {
  71579. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71580. this._onlefttriggerchanged(newValue);
  71581. }
  71582. this._leftTrigger = newValue;
  71583. },
  71584. enumerable: true,
  71585. configurable: true
  71586. });
  71587. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71588. /**
  71589. * Gets or sets right trigger value
  71590. */
  71591. get: function () {
  71592. return this._rightTrigger;
  71593. },
  71594. set: function (newValue) {
  71595. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71596. this._onrighttriggerchanged(newValue);
  71597. }
  71598. this._rightTrigger = newValue;
  71599. },
  71600. enumerable: true,
  71601. configurable: true
  71602. });
  71603. /**
  71604. * Defines the callback to call when a button is pressed
  71605. * @param callback defines the callback to use
  71606. */
  71607. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71608. this._onbuttondown = callback;
  71609. };
  71610. /**
  71611. * Defines the callback to call when a button is released
  71612. * @param callback defines the callback to use
  71613. */
  71614. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71615. this._onbuttonup = callback;
  71616. };
  71617. /**
  71618. * Defines the callback to call when a pad is pressed
  71619. * @param callback defines the callback to use
  71620. */
  71621. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71622. this._ondpaddown = callback;
  71623. };
  71624. /**
  71625. * Defines the callback to call when a pad is released
  71626. * @param callback defines the callback to use
  71627. */
  71628. Xbox360Pad.prototype.ondpadup = function (callback) {
  71629. this._ondpadup = callback;
  71630. };
  71631. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71632. if (newValue !== currentValue) {
  71633. if (newValue === 1) {
  71634. if (this._onbuttondown) {
  71635. this._onbuttondown(buttonType);
  71636. }
  71637. this.onButtonDownObservable.notifyObservers(buttonType);
  71638. }
  71639. if (newValue === 0) {
  71640. if (this._onbuttonup) {
  71641. this._onbuttonup(buttonType);
  71642. }
  71643. this.onButtonUpObservable.notifyObservers(buttonType);
  71644. }
  71645. }
  71646. return newValue;
  71647. };
  71648. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71649. if (newValue !== currentValue) {
  71650. if (newValue === 1) {
  71651. if (this._ondpaddown) {
  71652. this._ondpaddown(buttonType);
  71653. }
  71654. this.onPadDownObservable.notifyObservers(buttonType);
  71655. }
  71656. if (newValue === 0) {
  71657. if (this._ondpadup) {
  71658. this._ondpadup(buttonType);
  71659. }
  71660. this.onPadUpObservable.notifyObservers(buttonType);
  71661. }
  71662. }
  71663. return newValue;
  71664. };
  71665. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71666. /** Gets or sets value of A button */
  71667. get: function () {
  71668. return this._buttonA;
  71669. },
  71670. set: function (value) {
  71671. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71672. },
  71673. enumerable: true,
  71674. configurable: true
  71675. });
  71676. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71677. /** Gets or sets value of B button */
  71678. get: function () {
  71679. return this._buttonB;
  71680. },
  71681. set: function (value) {
  71682. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71683. },
  71684. enumerable: true,
  71685. configurable: true
  71686. });
  71687. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71688. /** Gets or sets value of X button */
  71689. get: function () {
  71690. return this._buttonX;
  71691. },
  71692. set: function (value) {
  71693. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71694. },
  71695. enumerable: true,
  71696. configurable: true
  71697. });
  71698. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71699. /** Gets or sets value of Y button */
  71700. get: function () {
  71701. return this._buttonY;
  71702. },
  71703. set: function (value) {
  71704. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71705. },
  71706. enumerable: true,
  71707. configurable: true
  71708. });
  71709. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71710. /** Gets or sets value of Start button */
  71711. get: function () {
  71712. return this._buttonStart;
  71713. },
  71714. set: function (value) {
  71715. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71716. },
  71717. enumerable: true,
  71718. configurable: true
  71719. });
  71720. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71721. /** Gets or sets value of Back button */
  71722. get: function () {
  71723. return this._buttonBack;
  71724. },
  71725. set: function (value) {
  71726. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71727. },
  71728. enumerable: true,
  71729. configurable: true
  71730. });
  71731. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71732. /** Gets or sets value of Left button */
  71733. get: function () {
  71734. return this._buttonLB;
  71735. },
  71736. set: function (value) {
  71737. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71738. },
  71739. enumerable: true,
  71740. configurable: true
  71741. });
  71742. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71743. /** Gets or sets value of Right button */
  71744. get: function () {
  71745. return this._buttonRB;
  71746. },
  71747. set: function (value) {
  71748. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71749. },
  71750. enumerable: true,
  71751. configurable: true
  71752. });
  71753. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71754. /** Gets or sets value of left stick */
  71755. get: function () {
  71756. return this._buttonLeftStick;
  71757. },
  71758. set: function (value) {
  71759. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71760. },
  71761. enumerable: true,
  71762. configurable: true
  71763. });
  71764. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71765. /** Gets or sets value of right stick */
  71766. get: function () {
  71767. return this._buttonRightStick;
  71768. },
  71769. set: function (value) {
  71770. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71771. },
  71772. enumerable: true,
  71773. configurable: true
  71774. });
  71775. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71776. /** Gets or sets value of DPad up */
  71777. get: function () {
  71778. return this._dPadUp;
  71779. },
  71780. set: function (value) {
  71781. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71782. },
  71783. enumerable: true,
  71784. configurable: true
  71785. });
  71786. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71787. /** Gets or sets value of DPad down */
  71788. get: function () {
  71789. return this._dPadDown;
  71790. },
  71791. set: function (value) {
  71792. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71793. },
  71794. enumerable: true,
  71795. configurable: true
  71796. });
  71797. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71798. /** Gets or sets value of DPad left */
  71799. get: function () {
  71800. return this._dPadLeft;
  71801. },
  71802. set: function (value) {
  71803. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71804. },
  71805. enumerable: true,
  71806. configurable: true
  71807. });
  71808. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71809. /** Gets or sets value of DPad right */
  71810. get: function () {
  71811. return this._dPadRight;
  71812. },
  71813. set: function (value) {
  71814. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71815. },
  71816. enumerable: true,
  71817. configurable: true
  71818. });
  71819. /**
  71820. * Force the gamepad to synchronize with device values
  71821. */
  71822. Xbox360Pad.prototype.update = function () {
  71823. _super.prototype.update.call(this);
  71824. if (this._isXboxOnePad) {
  71825. this.buttonA = this.browserGamepad.buttons[0].value;
  71826. this.buttonB = this.browserGamepad.buttons[1].value;
  71827. this.buttonX = this.browserGamepad.buttons[2].value;
  71828. this.buttonY = this.browserGamepad.buttons[3].value;
  71829. this.buttonLB = this.browserGamepad.buttons[4].value;
  71830. this.buttonRB = this.browserGamepad.buttons[5].value;
  71831. this.leftTrigger = this.browserGamepad.axes[2];
  71832. this.rightTrigger = this.browserGamepad.axes[5];
  71833. this.buttonBack = this.browserGamepad.buttons[9].value;
  71834. this.buttonStart = this.browserGamepad.buttons[8].value;
  71835. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71836. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71837. this.dPadUp = this.browserGamepad.buttons[11].value;
  71838. this.dPadDown = this.browserGamepad.buttons[12].value;
  71839. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71840. this.dPadRight = this.browserGamepad.buttons[14].value;
  71841. }
  71842. else {
  71843. this.buttonA = this.browserGamepad.buttons[0].value;
  71844. this.buttonB = this.browserGamepad.buttons[1].value;
  71845. this.buttonX = this.browserGamepad.buttons[2].value;
  71846. this.buttonY = this.browserGamepad.buttons[3].value;
  71847. this.buttonLB = this.browserGamepad.buttons[4].value;
  71848. this.buttonRB = this.browserGamepad.buttons[5].value;
  71849. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71850. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71851. this.buttonBack = this.browserGamepad.buttons[8].value;
  71852. this.buttonStart = this.browserGamepad.buttons[9].value;
  71853. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71854. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71855. this.dPadUp = this.browserGamepad.buttons[12].value;
  71856. this.dPadDown = this.browserGamepad.buttons[13].value;
  71857. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71858. this.dPadRight = this.browserGamepad.buttons[15].value;
  71859. }
  71860. };
  71861. Xbox360Pad.prototype.dispose = function () {
  71862. _super.prototype.dispose.call(this);
  71863. this.onButtonDownObservable.clear();
  71864. this.onButtonUpObservable.clear();
  71865. this.onPadDownObservable.clear();
  71866. this.onPadUpObservable.clear();
  71867. };
  71868. return Xbox360Pad;
  71869. }(BABYLON.Gamepad));
  71870. BABYLON.Xbox360Pad = Xbox360Pad;
  71871. })(BABYLON || (BABYLON = {}));
  71872. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71873. var BABYLON;
  71874. (function (BABYLON) {
  71875. /**
  71876. * Defines the types of pose enabled controllers that are supported
  71877. */
  71878. var PoseEnabledControllerType;
  71879. (function (PoseEnabledControllerType) {
  71880. /**
  71881. * HTC Vive
  71882. */
  71883. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71884. /**
  71885. * Oculus Rift
  71886. */
  71887. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71888. /**
  71889. * Windows mixed reality
  71890. */
  71891. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71892. /**
  71893. * Samsung gear VR
  71894. */
  71895. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71896. /**
  71897. * Google Daydream
  71898. */
  71899. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71900. /**
  71901. * Generic
  71902. */
  71903. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71904. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71905. /**
  71906. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71907. */
  71908. var PoseEnabledControllerHelper = /** @class */ (function () {
  71909. function PoseEnabledControllerHelper() {
  71910. }
  71911. /**
  71912. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71913. * @param vrGamepad the gamepad to initialized
  71914. * @returns a vr controller of the type the gamepad identified as
  71915. */
  71916. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71917. // Oculus Touch
  71918. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71919. return new BABYLON.OculusTouchController(vrGamepad);
  71920. }
  71921. // Windows Mixed Reality controllers
  71922. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71923. return new BABYLON.WindowsMotionController(vrGamepad);
  71924. }
  71925. // HTC Vive
  71926. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71927. return new BABYLON.ViveController(vrGamepad);
  71928. }
  71929. // Samsung/Oculus Gear VR or Oculus Go
  71930. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71931. return new BABYLON.GearVRController(vrGamepad);
  71932. }
  71933. // Google Daydream
  71934. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71935. return new BABYLON.DaydreamController(vrGamepad);
  71936. }
  71937. // Generic
  71938. else {
  71939. return new BABYLON.GenericController(vrGamepad);
  71940. }
  71941. };
  71942. return PoseEnabledControllerHelper;
  71943. }());
  71944. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71945. /**
  71946. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71947. */
  71948. var PoseEnabledController = /** @class */ (function (_super) {
  71949. __extends(PoseEnabledController, _super);
  71950. /**
  71951. * Creates a new PoseEnabledController from a gamepad
  71952. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71953. */
  71954. function PoseEnabledController(browserGamepad) {
  71955. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71956. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71957. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71958. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71959. /**
  71960. * The device position in babylon space
  71961. */
  71962. _this.devicePosition = BABYLON.Vector3.Zero();
  71963. /**
  71964. * The device rotation in babylon space
  71965. */
  71966. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71967. /**
  71968. * The scale factor of the device in babylon space
  71969. */
  71970. _this.deviceScaleFactor = 1;
  71971. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71972. /**
  71973. * Internal, matrix used to convert room space to babylon space
  71974. */
  71975. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71976. /**
  71977. * Node to be used when casting a ray from the controller
  71978. */
  71979. _this._pointingPoseNode = null;
  71980. _this._workingMatrix = BABYLON.Matrix.Identity();
  71981. /**
  71982. * @hidden
  71983. */
  71984. _this._meshAttachedObservable = new BABYLON.Observable();
  71985. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71986. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71987. _this.position = BABYLON.Vector3.Zero();
  71988. _this.rotationQuaternion = new BABYLON.Quaternion();
  71989. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71990. _this._calculatedRotation = new BABYLON.Quaternion();
  71991. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71992. return _this;
  71993. }
  71994. /**
  71995. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71996. */
  71997. PoseEnabledController.prototype.update = function () {
  71998. _super.prototype.update.call(this);
  71999. this._updatePoseAndMesh();
  72000. };
  72001. /**
  72002. * Updates only the pose device and mesh without doing any button event checking
  72003. */
  72004. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  72005. var pose = this.browserGamepad.pose;
  72006. this.updateFromDevice(pose);
  72007. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  72008. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72009. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72010. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72011. if (this._mesh) {
  72012. this._mesh.position.copyFrom(this.devicePosition);
  72013. if (this._mesh.rotationQuaternion) {
  72014. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72015. }
  72016. }
  72017. };
  72018. /**
  72019. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72020. * @param poseData raw pose fromthe device
  72021. */
  72022. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  72023. if (poseData) {
  72024. this.rawPose = poseData;
  72025. if (poseData.position) {
  72026. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  72027. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  72028. this._deviceRoomPosition.z *= -1;
  72029. }
  72030. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  72031. this._calculatedPosition.addInPlace(this.position);
  72032. }
  72033. var pose = this.rawPose;
  72034. if (poseData.orientation && pose.orientation) {
  72035. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  72036. if (this._mesh) {
  72037. if (this._mesh.getScene().useRightHandedSystem) {
  72038. this._deviceRoomRotationQuaternion.z *= -1;
  72039. this._deviceRoomRotationQuaternion.w *= -1;
  72040. }
  72041. else {
  72042. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  72043. }
  72044. }
  72045. // if the camera is set, rotate to the camera's rotation
  72046. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  72047. }
  72048. }
  72049. };
  72050. /**
  72051. * Attaches a mesh to the controller
  72052. * @param mesh the mesh to be attached
  72053. */
  72054. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  72055. if (this._mesh) {
  72056. this._mesh.parent = null;
  72057. }
  72058. this._mesh = mesh;
  72059. if (this._poseControlledCamera) {
  72060. this._mesh.parent = this._poseControlledCamera;
  72061. }
  72062. if (!this._mesh.rotationQuaternion) {
  72063. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  72064. }
  72065. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  72066. this._updatePoseAndMesh();
  72067. if (this._pointingPoseNode) {
  72068. var parents = [];
  72069. var obj = this._pointingPoseNode;
  72070. while (obj.parent) {
  72071. parents.push(obj.parent);
  72072. obj = obj.parent;
  72073. }
  72074. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  72075. }
  72076. this._meshAttachedObservable.notifyObservers(mesh);
  72077. };
  72078. /**
  72079. * Attaches the controllers mesh to a camera
  72080. * @param camera the camera the mesh should be attached to
  72081. */
  72082. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  72083. this._poseControlledCamera = camera;
  72084. if (this._mesh) {
  72085. this._mesh.parent = this._poseControlledCamera;
  72086. }
  72087. };
  72088. /**
  72089. * Disposes of the controller
  72090. */
  72091. PoseEnabledController.prototype.dispose = function () {
  72092. if (this._mesh) {
  72093. this._mesh.dispose();
  72094. }
  72095. this._mesh = null;
  72096. _super.prototype.dispose.call(this);
  72097. };
  72098. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  72099. /**
  72100. * The mesh that is attached to the controller
  72101. */
  72102. get: function () {
  72103. return this._mesh;
  72104. },
  72105. enumerable: true,
  72106. configurable: true
  72107. });
  72108. /**
  72109. * Gets the ray of the controller in the direction the controller is pointing
  72110. * @param length the length the resulting ray should be
  72111. * @returns a ray in the direction the controller is pointing
  72112. */
  72113. PoseEnabledController.prototype.getForwardRay = function (length) {
  72114. if (length === void 0) { length = 100; }
  72115. if (!this.mesh) {
  72116. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  72117. }
  72118. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  72119. var origin = m.getTranslation();
  72120. var forward = new BABYLON.Vector3(0, 0, -1);
  72121. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72122. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72123. return new BABYLON.Ray(origin, direction, length);
  72124. };
  72125. /**
  72126. * Name of the child mesh that can be used to cast a ray from the controller
  72127. */
  72128. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  72129. return PoseEnabledController;
  72130. }(BABYLON.Gamepad));
  72131. BABYLON.PoseEnabledController = PoseEnabledController;
  72132. })(BABYLON || (BABYLON = {}));
  72133. //# sourceMappingURL=babylon.poseEnabledController.js.map
  72134. var BABYLON;
  72135. (function (BABYLON) {
  72136. /**
  72137. * Defines the WebVRController object that represents controllers tracked in 3D space
  72138. */
  72139. var WebVRController = /** @class */ (function (_super) {
  72140. __extends(WebVRController, _super);
  72141. /**
  72142. * Creates a new WebVRController from a gamepad
  72143. * @param vrGamepad the gamepad that the WebVRController should be created from
  72144. */
  72145. function WebVRController(vrGamepad) {
  72146. var _this = _super.call(this, vrGamepad) || this;
  72147. // Observables
  72148. /**
  72149. * Fired when the trigger state has changed
  72150. */
  72151. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  72152. /**
  72153. * Fired when the main button state has changed
  72154. */
  72155. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  72156. /**
  72157. * Fired when the secondary button state has changed
  72158. */
  72159. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  72160. /**
  72161. * Fired when the pad state has changed
  72162. */
  72163. _this.onPadStateChangedObservable = new BABYLON.Observable();
  72164. /**
  72165. * Fired when controllers stick values have changed
  72166. */
  72167. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  72168. /**
  72169. * X and Y axis corrisponding to the controllers joystick
  72170. */
  72171. _this.pad = { x: 0, y: 0 };
  72172. // avoid GC, store state in a tmp object
  72173. _this._changes = {
  72174. pressChanged: false,
  72175. touchChanged: false,
  72176. valueChanged: false,
  72177. changed: false
  72178. };
  72179. _this._buttons = new Array(vrGamepad.buttons.length);
  72180. _this.hand = vrGamepad.hand;
  72181. return _this;
  72182. }
  72183. /**
  72184. * Fired when a controller button's state has changed
  72185. * @param callback the callback containing the button that was modified
  72186. */
  72187. WebVRController.prototype.onButtonStateChange = function (callback) {
  72188. this._onButtonStateChange = callback;
  72189. };
  72190. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72191. /**
  72192. * The default controller model for the controller
  72193. */
  72194. get: function () {
  72195. return this._defaultModel;
  72196. },
  72197. enumerable: true,
  72198. configurable: true
  72199. });
  72200. /**
  72201. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72202. */
  72203. WebVRController.prototype.update = function () {
  72204. _super.prototype.update.call(this);
  72205. for (var index = 0; index < this._buttons.length; index++) {
  72206. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72207. }
  72208. ;
  72209. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72210. this.pad.x = this.leftStick.x;
  72211. this.pad.y = this.leftStick.y;
  72212. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72213. }
  72214. };
  72215. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72216. if (!newState) {
  72217. newState = {
  72218. pressed: false,
  72219. touched: false,
  72220. value: 0
  72221. };
  72222. }
  72223. if (!currentState) {
  72224. this._buttons[buttonIndex] = {
  72225. pressed: newState.pressed,
  72226. touched: newState.touched,
  72227. value: newState.value
  72228. };
  72229. return;
  72230. }
  72231. this._checkChanges(newState, currentState);
  72232. if (this._changes.changed) {
  72233. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72234. this._handleButtonChange(buttonIndex, newState, this._changes);
  72235. }
  72236. this._buttons[buttonIndex].pressed = newState.pressed;
  72237. this._buttons[buttonIndex].touched = newState.touched;
  72238. // oculus triggers are never 0, thou not touched.
  72239. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72240. };
  72241. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72242. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72243. this._changes.touchChanged = newState.touched !== currentState.touched;
  72244. this._changes.valueChanged = newState.value !== currentState.value;
  72245. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72246. return this._changes;
  72247. };
  72248. /**
  72249. * Disposes of th webVRCOntroller
  72250. */
  72251. WebVRController.prototype.dispose = function () {
  72252. _super.prototype.dispose.call(this);
  72253. this.onTriggerStateChangedObservable.clear();
  72254. this.onMainButtonStateChangedObservable.clear();
  72255. this.onSecondaryButtonStateChangedObservable.clear();
  72256. this.onPadStateChangedObservable.clear();
  72257. this.onPadValuesChangedObservable.clear();
  72258. };
  72259. return WebVRController;
  72260. }(BABYLON.PoseEnabledController));
  72261. BABYLON.WebVRController = WebVRController;
  72262. })(BABYLON || (BABYLON = {}));
  72263. //# sourceMappingURL=babylon.webVRController.js.map
  72264. var BABYLON;
  72265. (function (BABYLON) {
  72266. /**
  72267. * Oculus Touch Controller
  72268. */
  72269. var OculusTouchController = /** @class */ (function (_super) {
  72270. __extends(OculusTouchController, _super);
  72271. /**
  72272. * Creates a new OculusTouchController from a gamepad
  72273. * @param vrGamepad the gamepad that the controller should be created from
  72274. */
  72275. function OculusTouchController(vrGamepad) {
  72276. var _this = _super.call(this, vrGamepad) || this;
  72277. /**
  72278. * Fired when the secondary trigger on this controller is modified
  72279. */
  72280. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72281. /**
  72282. * Fired when the thumb rest on this controller is modified
  72283. */
  72284. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72285. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72286. return _this;
  72287. }
  72288. /**
  72289. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72290. * @param scene scene in which to add meshes
  72291. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72292. */
  72293. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72294. var _this = this;
  72295. var meshName;
  72296. // Hand
  72297. if (this.hand === 'left') {
  72298. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72299. }
  72300. else { // Right is the default if no hand is specified
  72301. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72302. }
  72303. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72304. /*
  72305. Parent Mesh name: oculus_touch_left
  72306. - body
  72307. - trigger
  72308. - thumbstick
  72309. - grip
  72310. - button_y
  72311. - button_x
  72312. - button_enter
  72313. */
  72314. _this._defaultModel = newMeshes[1];
  72315. _this.attachToMesh(_this._defaultModel);
  72316. if (meshLoaded) {
  72317. meshLoaded(_this._defaultModel);
  72318. }
  72319. });
  72320. };
  72321. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72322. /**
  72323. * Fired when the A button on this controller is modified
  72324. */
  72325. get: function () {
  72326. if (this.hand === 'right') {
  72327. return this.onMainButtonStateChangedObservable;
  72328. }
  72329. else {
  72330. throw new Error('No A button on left hand');
  72331. }
  72332. },
  72333. enumerable: true,
  72334. configurable: true
  72335. });
  72336. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72337. /**
  72338. * Fired when the B button on this controller is modified
  72339. */
  72340. get: function () {
  72341. if (this.hand === 'right') {
  72342. return this.onSecondaryButtonStateChangedObservable;
  72343. }
  72344. else {
  72345. throw new Error('No B button on left hand');
  72346. }
  72347. },
  72348. enumerable: true,
  72349. configurable: true
  72350. });
  72351. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72352. /**
  72353. * Fired when the X button on this controller is modified
  72354. */
  72355. get: function () {
  72356. if (this.hand === 'left') {
  72357. return this.onMainButtonStateChangedObservable;
  72358. }
  72359. else {
  72360. throw new Error('No X button on right hand');
  72361. }
  72362. },
  72363. enumerable: true,
  72364. configurable: true
  72365. });
  72366. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72367. /**
  72368. * Fired when the Y button on this controller is modified
  72369. */
  72370. get: function () {
  72371. if (this.hand === 'left') {
  72372. return this.onSecondaryButtonStateChangedObservable;
  72373. }
  72374. else {
  72375. throw new Error('No Y button on right hand');
  72376. }
  72377. },
  72378. enumerable: true,
  72379. configurable: true
  72380. });
  72381. /**
  72382. * Called once for each button that changed state since the last frame
  72383. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72384. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72385. * 2) secondary trigger (same)
  72386. * 3) A (right) X (left), touch, pressed = value
  72387. * 4) B / Y
  72388. * 5) thumb rest
  72389. * @param buttonIdx Which button index changed
  72390. * @param state New state of the button
  72391. * @param changes Which properties on the state changed since last frame
  72392. */
  72393. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72394. var notifyObject = state; //{ state: state, changes: changes };
  72395. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72396. switch (buttonIdx) {
  72397. case 0:
  72398. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72399. return;
  72400. case 1: // index trigger
  72401. if (this._defaultModel) {
  72402. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72403. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72404. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72405. }
  72406. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72407. return;
  72408. case 2: // secondary trigger
  72409. if (this._defaultModel) {
  72410. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72411. }
  72412. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72413. return;
  72414. case 3:
  72415. if (this._defaultModel) {
  72416. if (notifyObject.pressed) {
  72417. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72418. }
  72419. else {
  72420. (this._defaultModel.getChildren()[1]).position.y = 0;
  72421. }
  72422. }
  72423. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72424. return;
  72425. case 4:
  72426. if (this._defaultModel) {
  72427. if (notifyObject.pressed) {
  72428. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72429. }
  72430. else {
  72431. (this._defaultModel.getChildren()[2]).position.y = 0;
  72432. }
  72433. }
  72434. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72435. return;
  72436. case 5:
  72437. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72438. return;
  72439. }
  72440. };
  72441. /**
  72442. * Base Url for the controller model.
  72443. */
  72444. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72445. /**
  72446. * File name for the left controller model.
  72447. */
  72448. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72449. /**
  72450. * File name for the right controller model.
  72451. */
  72452. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72453. return OculusTouchController;
  72454. }(BABYLON.WebVRController));
  72455. BABYLON.OculusTouchController = OculusTouchController;
  72456. })(BABYLON || (BABYLON = {}));
  72457. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72458. var BABYLON;
  72459. (function (BABYLON) {
  72460. /**
  72461. * Vive Controller
  72462. */
  72463. var ViveController = /** @class */ (function (_super) {
  72464. __extends(ViveController, _super);
  72465. /**
  72466. * Creates a new ViveController from a gamepad
  72467. * @param vrGamepad the gamepad that the controller should be created from
  72468. */
  72469. function ViveController(vrGamepad) {
  72470. var _this = _super.call(this, vrGamepad) || this;
  72471. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72472. _this._invertLeftStickY = true;
  72473. return _this;
  72474. }
  72475. /**
  72476. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72477. * @param scene scene in which to add meshes
  72478. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72479. */
  72480. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72481. var _this = this;
  72482. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72483. /*
  72484. Parent Mesh name: ViveWand
  72485. - body
  72486. - r_gripper
  72487. - l_gripper
  72488. - menu_button
  72489. - system_button
  72490. - trackpad
  72491. - trigger
  72492. - LED
  72493. */
  72494. _this._defaultModel = newMeshes[1];
  72495. _this.attachToMesh(_this._defaultModel);
  72496. if (meshLoaded) {
  72497. meshLoaded(_this._defaultModel);
  72498. }
  72499. });
  72500. };
  72501. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72502. /**
  72503. * Fired when the left button on this controller is modified
  72504. */
  72505. get: function () {
  72506. return this.onMainButtonStateChangedObservable;
  72507. },
  72508. enumerable: true,
  72509. configurable: true
  72510. });
  72511. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72512. /**
  72513. * Fired when the right button on this controller is modified
  72514. */
  72515. get: function () {
  72516. return this.onMainButtonStateChangedObservable;
  72517. },
  72518. enumerable: true,
  72519. configurable: true
  72520. });
  72521. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72522. /**
  72523. * Fired when the menu button on this controller is modified
  72524. */
  72525. get: function () {
  72526. return this.onSecondaryButtonStateChangedObservable;
  72527. },
  72528. enumerable: true,
  72529. configurable: true
  72530. });
  72531. /**
  72532. * Called once for each button that changed state since the last frame
  72533. * Vive mapping:
  72534. * 0: touchpad
  72535. * 1: trigger
  72536. * 2: left AND right buttons
  72537. * 3: menu button
  72538. * @param buttonIdx Which button index changed
  72539. * @param state New state of the button
  72540. * @param changes Which properties on the state changed since last frame
  72541. */
  72542. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72543. var notifyObject = state; //{ state: state, changes: changes };
  72544. switch (buttonIdx) {
  72545. case 0:
  72546. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72547. return;
  72548. case 1: // index trigger
  72549. if (this._defaultModel) {
  72550. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72551. }
  72552. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72553. return;
  72554. case 2: // left AND right button
  72555. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72556. return;
  72557. case 3:
  72558. if (this._defaultModel) {
  72559. if (notifyObject.pressed) {
  72560. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72561. }
  72562. else {
  72563. (this._defaultModel.getChildren()[2]).position.y = 0;
  72564. }
  72565. }
  72566. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72567. return;
  72568. }
  72569. };
  72570. /**
  72571. * Base Url for the controller model.
  72572. */
  72573. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72574. /**
  72575. * File name for the controller model.
  72576. */
  72577. ViveController.MODEL_FILENAME = 'wand.babylon';
  72578. return ViveController;
  72579. }(BABYLON.WebVRController));
  72580. BABYLON.ViveController = ViveController;
  72581. })(BABYLON || (BABYLON = {}));
  72582. //# sourceMappingURL=babylon.viveController.js.map
  72583. var BABYLON;
  72584. (function (BABYLON) {
  72585. /**
  72586. * Generic Controller
  72587. */
  72588. var GenericController = /** @class */ (function (_super) {
  72589. __extends(GenericController, _super);
  72590. /**
  72591. * Creates a new GenericController from a gamepad
  72592. * @param vrGamepad the gamepad that the controller should be created from
  72593. */
  72594. function GenericController(vrGamepad) {
  72595. return _super.call(this, vrGamepad) || this;
  72596. }
  72597. /**
  72598. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72599. * @param scene scene in which to add meshes
  72600. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72601. */
  72602. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72603. var _this = this;
  72604. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72605. _this._defaultModel = newMeshes[1];
  72606. _this.attachToMesh(_this._defaultModel);
  72607. if (meshLoaded) {
  72608. meshLoaded(_this._defaultModel);
  72609. }
  72610. });
  72611. };
  72612. /**
  72613. * Called once for each button that changed state since the last frame
  72614. * @param buttonIdx Which button index changed
  72615. * @param state New state of the button
  72616. * @param changes Which properties on the state changed since last frame
  72617. */
  72618. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72619. console.log("Button id: " + buttonIdx + "state: ");
  72620. console.dir(state);
  72621. };
  72622. /**
  72623. * Base Url for the controller model.
  72624. */
  72625. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72626. /**
  72627. * File name for the controller model.
  72628. */
  72629. GenericController.MODEL_FILENAME = 'generic.babylon';
  72630. return GenericController;
  72631. }(BABYLON.WebVRController));
  72632. BABYLON.GenericController = GenericController;
  72633. })(BABYLON || (BABYLON = {}));
  72634. //# sourceMappingURL=babylon.genericController.js.map
  72635. var BABYLON;
  72636. (function (BABYLON) {
  72637. /**
  72638. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72639. */
  72640. var LoadedMeshInfo = /** @class */ (function () {
  72641. function LoadedMeshInfo() {
  72642. /**
  72643. * Map of the button meshes contained in the controller
  72644. */
  72645. this.buttonMeshes = {};
  72646. /**
  72647. * Map of the axis meshes contained in the controller
  72648. */
  72649. this.axisMeshes = {};
  72650. }
  72651. return LoadedMeshInfo;
  72652. }());
  72653. /**
  72654. * Defines the WindowsMotionController object that the state of the windows motion controller
  72655. */
  72656. var WindowsMotionController = /** @class */ (function (_super) {
  72657. __extends(WindowsMotionController, _super);
  72658. /**
  72659. * Creates a new WindowsMotionController from a gamepad
  72660. * @param vrGamepad the gamepad that the controller should be created from
  72661. */
  72662. function WindowsMotionController(vrGamepad) {
  72663. var _this = _super.call(this, vrGamepad) || this;
  72664. _this._mapping = {
  72665. // Semantic button names
  72666. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72667. // A mapping of the button name to glTF model node name
  72668. // that should be transformed by button value.
  72669. buttonMeshNames: {
  72670. 'trigger': 'SELECT',
  72671. 'menu': 'MENU',
  72672. 'grip': 'GRASP',
  72673. 'thumbstick': 'THUMBSTICK_PRESS',
  72674. 'trackpad': 'TOUCHPAD_PRESS'
  72675. },
  72676. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72677. buttonObservableNames: {
  72678. 'trigger': 'onTriggerStateChangedObservable',
  72679. 'menu': 'onSecondaryButtonStateChangedObservable',
  72680. 'grip': 'onMainButtonStateChangedObservable',
  72681. 'thumbstick': 'onPadStateChangedObservable',
  72682. 'trackpad': 'onTrackpadChangedObservable'
  72683. },
  72684. // A mapping of the axis name to glTF model node name
  72685. // that should be transformed by axis value.
  72686. // This array mirrors the browserGamepad.axes array, such that
  72687. // the mesh corresponding to axis 0 is in this array index 0.
  72688. axisMeshNames: [
  72689. 'THUMBSTICK_X',
  72690. 'THUMBSTICK_Y',
  72691. 'TOUCHPAD_TOUCH_X',
  72692. 'TOUCHPAD_TOUCH_Y'
  72693. ],
  72694. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72695. };
  72696. /**
  72697. * Fired when the trackpad on this controller is clicked
  72698. */
  72699. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72700. /**
  72701. * Fired when the trackpad on this controller is modified
  72702. */
  72703. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72704. /**
  72705. * The current x and y values of this controller's trackpad
  72706. */
  72707. _this.trackpad = { x: 0, y: 0 };
  72708. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72709. _this._loadedMeshInfo = null;
  72710. return _this;
  72711. }
  72712. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72713. /**
  72714. * Fired when the trigger on this controller is modified
  72715. */
  72716. get: function () {
  72717. return this.onTriggerStateChangedObservable;
  72718. },
  72719. enumerable: true,
  72720. configurable: true
  72721. });
  72722. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72723. /**
  72724. * Fired when the menu button on this controller is modified
  72725. */
  72726. get: function () {
  72727. return this.onSecondaryButtonStateChangedObservable;
  72728. },
  72729. enumerable: true,
  72730. configurable: true
  72731. });
  72732. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72733. /**
  72734. * Fired when the grip button on this controller is modified
  72735. */
  72736. get: function () {
  72737. return this.onMainButtonStateChangedObservable;
  72738. },
  72739. enumerable: true,
  72740. configurable: true
  72741. });
  72742. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72743. /**
  72744. * Fired when the thumbstick button on this controller is modified
  72745. */
  72746. get: function () {
  72747. return this.onPadStateChangedObservable;
  72748. },
  72749. enumerable: true,
  72750. configurable: true
  72751. });
  72752. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72753. /**
  72754. * Fired when the touchpad button on this controller is modified
  72755. */
  72756. get: function () {
  72757. return this.onTrackpadChangedObservable;
  72758. },
  72759. enumerable: true,
  72760. configurable: true
  72761. });
  72762. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72763. /**
  72764. * Fired when the touchpad values on this controller are modified
  72765. */
  72766. get: function () {
  72767. return this.onTrackpadValuesChangedObservable;
  72768. },
  72769. enumerable: true,
  72770. configurable: true
  72771. });
  72772. WindowsMotionController.prototype._updateTrackpad = function () {
  72773. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72774. this.trackpad.x = this.browserGamepad["axes"][2];
  72775. this.trackpad.y = this.browserGamepad["axes"][3];
  72776. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72777. }
  72778. };
  72779. /**
  72780. * Called once per frame by the engine.
  72781. */
  72782. WindowsMotionController.prototype.update = function () {
  72783. _super.prototype.update.call(this);
  72784. if (this.browserGamepad.axes) {
  72785. this._updateTrackpad();
  72786. // Only need to animate axes if there is a loaded mesh
  72787. if (this._loadedMeshInfo) {
  72788. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72789. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72790. }
  72791. }
  72792. }
  72793. };
  72794. /**
  72795. * Called once for each button that changed state since the last frame
  72796. * @param buttonIdx Which button index changed
  72797. * @param state New state of the button
  72798. * @param changes Which properties on the state changed since last frame
  72799. */
  72800. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72801. var buttonName = this._mapping.buttons[buttonIdx];
  72802. if (!buttonName) {
  72803. return;
  72804. }
  72805. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72806. this._updateTrackpad();
  72807. // Only emit events for buttons that we know how to map from index to name
  72808. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72809. if (observable) {
  72810. observable.notifyObservers(state);
  72811. }
  72812. this._lerpButtonTransform(buttonName, state.value);
  72813. };
  72814. /**
  72815. * Moves the buttons on the controller mesh based on their current state
  72816. * @param buttonName the name of the button to move
  72817. * @param buttonValue the value of the button which determines the buttons new position
  72818. */
  72819. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72820. // If there is no loaded mesh, there is nothing to transform.
  72821. if (!this._loadedMeshInfo) {
  72822. return;
  72823. }
  72824. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72825. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72826. return;
  72827. }
  72828. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72829. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72830. };
  72831. /**
  72832. * Moves the axis on the controller mesh based on its current state
  72833. * @param axis the index of the axis
  72834. * @param axisValue the value of the axis which determines the meshes new position
  72835. * @hidden
  72836. */
  72837. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72838. if (!this._loadedMeshInfo) {
  72839. return;
  72840. }
  72841. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72842. if (!meshInfo) {
  72843. return;
  72844. }
  72845. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72846. return;
  72847. }
  72848. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72849. var lerpValue = axisValue * 0.5 + 0.5;
  72850. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72851. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72852. };
  72853. /**
  72854. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72855. * @param scene scene in which to add meshes
  72856. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72857. */
  72858. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72859. var _this = this;
  72860. if (forceDefault === void 0) { forceDefault = false; }
  72861. var path;
  72862. var filename;
  72863. // Checking if GLB loader is present
  72864. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72865. // Determine the device specific folder based on the ID suffix
  72866. var device = 'default';
  72867. if (this.id && !forceDefault) {
  72868. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72869. device = ((match && match[0]) || device);
  72870. }
  72871. // Hand
  72872. if (this.hand === 'left') {
  72873. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72874. }
  72875. else { // Right is the default if no hand is specified
  72876. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72877. }
  72878. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72879. }
  72880. else {
  72881. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72882. path = BABYLON.GenericController.MODEL_BASE_URL;
  72883. filename = BABYLON.GenericController.MODEL_FILENAME;
  72884. }
  72885. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72886. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72887. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72888. if (!_this._loadedMeshInfo) {
  72889. return;
  72890. }
  72891. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72892. _this.attachToMesh(_this._defaultModel);
  72893. if (meshLoaded) {
  72894. meshLoaded(_this._defaultModel);
  72895. }
  72896. }, null, function (scene, message) {
  72897. BABYLON.Tools.Log(message);
  72898. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72899. if (!forceDefault) {
  72900. _this.initControllerMesh(scene, meshLoaded, true);
  72901. }
  72902. });
  72903. };
  72904. /**
  72905. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72906. * can be transformed by button presses and axes values, based on this._mapping.
  72907. *
  72908. * @param scene scene in which the meshes exist
  72909. * @param meshes list of meshes that make up the controller model to process
  72910. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72911. */
  72912. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72913. var loadedMeshInfo = null;
  72914. // Create a new mesh to contain the glTF hierarchy
  72915. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72916. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72917. var childMesh = null;
  72918. for (var i = 0; i < meshes.length; i++) {
  72919. var mesh = meshes[i];
  72920. if (!mesh.parent) {
  72921. // Exclude controller meshes from picking results
  72922. mesh.isPickable = false;
  72923. // Handle root node, attach to the new parentMesh
  72924. childMesh = mesh;
  72925. break;
  72926. }
  72927. }
  72928. if (childMesh) {
  72929. childMesh.setParent(parentMesh);
  72930. // Create our mesh info. Note that this method will always return non-null.
  72931. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72932. }
  72933. else {
  72934. BABYLON.Tools.Warn('Could not find root node in model file.');
  72935. }
  72936. return loadedMeshInfo;
  72937. };
  72938. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72939. var loadedMeshInfo = new LoadedMeshInfo();
  72940. var i;
  72941. loadedMeshInfo.rootNode = rootNode;
  72942. // Reset the caches
  72943. loadedMeshInfo.buttonMeshes = {};
  72944. loadedMeshInfo.axisMeshes = {};
  72945. // Button Meshes
  72946. for (i = 0; i < this._mapping.buttons.length; i++) {
  72947. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72948. if (!buttonMeshName) {
  72949. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72950. continue;
  72951. }
  72952. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72953. if (!buttonMesh) {
  72954. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72955. continue;
  72956. }
  72957. var buttonMeshInfo = {
  72958. index: i,
  72959. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72960. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72961. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72962. };
  72963. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72964. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72965. }
  72966. else {
  72967. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72968. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72969. '(VALUE: ' + !!buttonMeshInfo.value +
  72970. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72971. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72972. ')');
  72973. }
  72974. }
  72975. // Axis Meshes
  72976. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72977. var axisMeshName = this._mapping.axisMeshNames[i];
  72978. if (!axisMeshName) {
  72979. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72980. continue;
  72981. }
  72982. var axisMesh = getChildByName(rootNode, axisMeshName);
  72983. if (!axisMesh) {
  72984. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72985. continue;
  72986. }
  72987. var axisMeshInfo = {
  72988. index: i,
  72989. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72990. min: getImmediateChildByName(axisMesh, 'MIN'),
  72991. max: getImmediateChildByName(axisMesh, 'MAX')
  72992. };
  72993. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72994. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72995. }
  72996. else {
  72997. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72998. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72999. '(VALUE: ' + !!axisMeshInfo.value +
  73000. ', MIN: ' + !!axisMeshInfo.min +
  73001. ', MAX:' + !!axisMeshInfo.max +
  73002. ')');
  73003. }
  73004. }
  73005. // Pointing Ray
  73006. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  73007. if (!loadedMeshInfo.pointingPoseNode) {
  73008. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73009. }
  73010. else {
  73011. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73012. }
  73013. return loadedMeshInfo;
  73014. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73015. function getChildByName(node, name) {
  73016. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73017. }
  73018. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73019. function getImmediateChildByName(node, name) {
  73020. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73021. }
  73022. };
  73023. /**
  73024. * Gets the ray of the controller in the direction the controller is pointing
  73025. * @param length the length the resulting ray should be
  73026. * @returns a ray in the direction the controller is pointing
  73027. */
  73028. WindowsMotionController.prototype.getForwardRay = function (length) {
  73029. if (length === void 0) { length = 100; }
  73030. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  73031. return _super.prototype.getForwardRay.call(this, length);
  73032. }
  73033. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  73034. var origin = m.getTranslation();
  73035. var forward = new BABYLON.Vector3(0, 0, -1);
  73036. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73037. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73038. return new BABYLON.Ray(origin, direction, length);
  73039. };
  73040. /**
  73041. * Disposes of the controller
  73042. */
  73043. WindowsMotionController.prototype.dispose = function () {
  73044. _super.prototype.dispose.call(this);
  73045. this.onTrackpadChangedObservable.clear();
  73046. };
  73047. /**
  73048. * The base url used to load the left and right controller models
  73049. */
  73050. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  73051. /**
  73052. * The name of the left controller model file
  73053. */
  73054. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  73055. /**
  73056. * The name of the right controller model file
  73057. */
  73058. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  73059. /**
  73060. * The controller name prefix for this controller type
  73061. */
  73062. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  73063. /**
  73064. * The controller id pattern for this controller type
  73065. */
  73066. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  73067. return WindowsMotionController;
  73068. }(BABYLON.WebVRController));
  73069. BABYLON.WindowsMotionController = WindowsMotionController;
  73070. })(BABYLON || (BABYLON = {}));
  73071. //# sourceMappingURL=babylon.windowsMotionController.js.map
  73072. var BABYLON;
  73073. (function (BABYLON) {
  73074. /**
  73075. * Gear VR Controller
  73076. */
  73077. var GearVRController = /** @class */ (function (_super) {
  73078. __extends(GearVRController, _super);
  73079. /**
  73080. * Creates a new GearVRController from a gamepad
  73081. * @param vrGamepad the gamepad that the controller should be created from
  73082. */
  73083. function GearVRController(vrGamepad) {
  73084. var _this = _super.call(this, vrGamepad) || this;
  73085. _this._buttonIndexToObservableNameMap = [
  73086. 'onTrackpadChangedObservable',
  73087. 'onTriggerStateChangedObservable' // Trigger
  73088. ];
  73089. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  73090. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  73091. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  73092. return _this;
  73093. }
  73094. /**
  73095. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73096. * @param scene scene in which to add meshes
  73097. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73098. */
  73099. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73100. var _this = this;
  73101. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  73102. _this._defaultModel = newMeshes[1];
  73103. _this.attachToMesh(_this._defaultModel);
  73104. if (meshLoaded) {
  73105. meshLoaded(_this._defaultModel);
  73106. }
  73107. });
  73108. };
  73109. /**
  73110. * Called once for each button that changed state since the last frame
  73111. * @param buttonIdx Which button index changed
  73112. * @param state New state of the button
  73113. * @param changes Which properties on the state changed since last frame
  73114. */
  73115. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73116. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  73117. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  73118. // Only emit events for buttons that we know how to map from index to observable
  73119. var observable = this[observableName];
  73120. if (observable) {
  73121. observable.notifyObservers(state);
  73122. }
  73123. }
  73124. };
  73125. /**
  73126. * Base Url for the controller model.
  73127. */
  73128. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73129. /**
  73130. * File name for the controller model.
  73131. */
  73132. GearVRController.MODEL_FILENAME = 'generic.babylon';
  73133. /**
  73134. * Gamepad Id prefix used to identify this controller.
  73135. */
  73136. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  73137. return GearVRController;
  73138. }(BABYLON.WebVRController));
  73139. BABYLON.GearVRController = GearVRController;
  73140. })(BABYLON || (BABYLON = {}));
  73141. //# sourceMappingURL=babylon.gearVRController.js.map
  73142. var BABYLON;
  73143. (function (BABYLON) {
  73144. /**
  73145. * Google Daydream controller
  73146. */
  73147. var DaydreamController = /** @class */ (function (_super) {
  73148. __extends(DaydreamController, _super);
  73149. /**
  73150. * Creates a new DaydreamController from a gamepad
  73151. * @param vrGamepad the gamepad that the controller should be created from
  73152. */
  73153. function DaydreamController(vrGamepad) {
  73154. var _this = _super.call(this, vrGamepad) || this;
  73155. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  73156. return _this;
  73157. }
  73158. /**
  73159. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73160. * @param scene scene in which to add meshes
  73161. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73162. */
  73163. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73164. var _this = this;
  73165. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  73166. _this._defaultModel = newMeshes[1];
  73167. _this.attachToMesh(_this._defaultModel);
  73168. if (meshLoaded) {
  73169. meshLoaded(_this._defaultModel);
  73170. }
  73171. });
  73172. };
  73173. /**
  73174. * Called once for each button that changed state since the last frame
  73175. * @param buttonIdx Which button index changed
  73176. * @param state New state of the button
  73177. * @param changes Which properties on the state changed since last frame
  73178. */
  73179. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73180. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73181. if (buttonIdx === 0) {
  73182. var observable = this.onTriggerStateChangedObservable;
  73183. if (observable) {
  73184. observable.notifyObservers(state);
  73185. }
  73186. }
  73187. else {
  73188. // If the app or home buttons are ever made available
  73189. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73190. }
  73191. };
  73192. /**
  73193. * Base Url for the controller model.
  73194. */
  73195. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73196. /**
  73197. * File name for the controller model.
  73198. */
  73199. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73200. /**
  73201. * Gamepad Id prefix used to identify Daydream Controller.
  73202. */
  73203. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73204. return DaydreamController;
  73205. }(BABYLON.WebVRController));
  73206. BABYLON.DaydreamController = DaydreamController;
  73207. })(BABYLON || (BABYLON = {}));
  73208. //# sourceMappingURL=babylon.daydreamController.js.map
  73209. var BABYLON;
  73210. (function (BABYLON) {
  73211. var FollowCamera = /** @class */ (function (_super) {
  73212. __extends(FollowCamera, _super);
  73213. function FollowCamera(name, position, scene, lockedTarget) {
  73214. if (lockedTarget === void 0) { lockedTarget = null; }
  73215. var _this = _super.call(this, name, position, scene) || this;
  73216. _this.radius = 12;
  73217. _this.rotationOffset = 0;
  73218. _this.heightOffset = 4;
  73219. _this.cameraAcceleration = 0.05;
  73220. _this.maxCameraSpeed = 20;
  73221. _this.lockedTarget = lockedTarget;
  73222. return _this;
  73223. }
  73224. FollowCamera.prototype.getRadians = function (degrees) {
  73225. return degrees * Math.PI / 180;
  73226. };
  73227. FollowCamera.prototype.follow = function (cameraTarget) {
  73228. if (!cameraTarget)
  73229. return;
  73230. var yRotation;
  73231. if (cameraTarget.rotationQuaternion) {
  73232. var rotMatrix = new BABYLON.Matrix();
  73233. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73234. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73235. }
  73236. else {
  73237. yRotation = cameraTarget.rotation.y;
  73238. }
  73239. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73240. var targetPosition = cameraTarget.getAbsolutePosition();
  73241. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73242. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73243. var dx = targetX - this.position.x;
  73244. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73245. var dz = (targetZ) - this.position.z;
  73246. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73247. var vy = dy * this.cameraAcceleration;
  73248. var vz = dz * this.cameraAcceleration * 2;
  73249. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73250. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73251. }
  73252. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73253. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73254. }
  73255. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73256. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73257. }
  73258. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73259. this.setTarget(targetPosition);
  73260. };
  73261. FollowCamera.prototype._checkInputs = function () {
  73262. _super.prototype._checkInputs.call(this);
  73263. if (this.lockedTarget) {
  73264. this.follow(this.lockedTarget);
  73265. }
  73266. };
  73267. FollowCamera.prototype.getClassName = function () {
  73268. return "FollowCamera";
  73269. };
  73270. __decorate([
  73271. BABYLON.serialize()
  73272. ], FollowCamera.prototype, "radius", void 0);
  73273. __decorate([
  73274. BABYLON.serialize()
  73275. ], FollowCamera.prototype, "rotationOffset", void 0);
  73276. __decorate([
  73277. BABYLON.serialize()
  73278. ], FollowCamera.prototype, "heightOffset", void 0);
  73279. __decorate([
  73280. BABYLON.serialize()
  73281. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73282. __decorate([
  73283. BABYLON.serialize()
  73284. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73285. __decorate([
  73286. BABYLON.serializeAsMeshReference("lockedTargetId")
  73287. ], FollowCamera.prototype, "lockedTarget", void 0);
  73288. return FollowCamera;
  73289. }(BABYLON.TargetCamera));
  73290. BABYLON.FollowCamera = FollowCamera;
  73291. var ArcFollowCamera = /** @class */ (function (_super) {
  73292. __extends(ArcFollowCamera, _super);
  73293. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73294. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73295. _this.alpha = alpha;
  73296. _this.beta = beta;
  73297. _this.radius = radius;
  73298. _this.target = target;
  73299. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73300. _this.follow();
  73301. return _this;
  73302. }
  73303. ArcFollowCamera.prototype.follow = function () {
  73304. if (!this.target) {
  73305. return;
  73306. }
  73307. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73308. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73309. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73310. var targetPosition = this.target.getAbsolutePosition();
  73311. this.position = targetPosition.add(this._cartesianCoordinates);
  73312. this.setTarget(targetPosition);
  73313. };
  73314. ArcFollowCamera.prototype._checkInputs = function () {
  73315. _super.prototype._checkInputs.call(this);
  73316. this.follow();
  73317. };
  73318. ArcFollowCamera.prototype.getClassName = function () {
  73319. return "ArcFollowCamera";
  73320. };
  73321. return ArcFollowCamera;
  73322. }(BABYLON.TargetCamera));
  73323. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73324. })(BABYLON || (BABYLON = {}));
  73325. //# sourceMappingURL=babylon.followCamera.js.map
  73326. var BABYLON;
  73327. (function (BABYLON) {
  73328. // We're mainly based on the logic defined into the FreeCamera code
  73329. var UniversalCamera = /** @class */ (function (_super) {
  73330. __extends(UniversalCamera, _super);
  73331. //-- end properties for backward compatibility for inputs
  73332. function UniversalCamera(name, position, scene) {
  73333. var _this = _super.call(this, name, position, scene) || this;
  73334. _this.inputs.addGamepad();
  73335. return _this;
  73336. }
  73337. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73338. //-- Begin properties for backward compatibility for inputs
  73339. get: function () {
  73340. var gamepad = this.inputs.attached["gamepad"];
  73341. if (gamepad)
  73342. return gamepad.gamepadAngularSensibility;
  73343. return 0;
  73344. },
  73345. set: function (value) {
  73346. var gamepad = this.inputs.attached["gamepad"];
  73347. if (gamepad)
  73348. gamepad.gamepadAngularSensibility = value;
  73349. },
  73350. enumerable: true,
  73351. configurable: true
  73352. });
  73353. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73354. get: function () {
  73355. var gamepad = this.inputs.attached["gamepad"];
  73356. if (gamepad)
  73357. return gamepad.gamepadMoveSensibility;
  73358. return 0;
  73359. },
  73360. set: function (value) {
  73361. var gamepad = this.inputs.attached["gamepad"];
  73362. if (gamepad)
  73363. gamepad.gamepadMoveSensibility = value;
  73364. },
  73365. enumerable: true,
  73366. configurable: true
  73367. });
  73368. UniversalCamera.prototype.getClassName = function () {
  73369. return "UniversalCamera";
  73370. };
  73371. return UniversalCamera;
  73372. }(BABYLON.TouchCamera));
  73373. BABYLON.UniversalCamera = UniversalCamera;
  73374. })(BABYLON || (BABYLON = {}));
  73375. //# sourceMappingURL=babylon.universalCamera.js.map
  73376. var BABYLON;
  73377. (function (BABYLON) {
  73378. // We're mainly based on the logic defined into the FreeCamera code
  73379. var GamepadCamera = /** @class */ (function (_super) {
  73380. __extends(GamepadCamera, _super);
  73381. //-- end properties for backward compatibility for inputs
  73382. function GamepadCamera(name, position, scene) {
  73383. return _super.call(this, name, position, scene) || this;
  73384. }
  73385. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73386. //-- Begin properties for backward compatibility for inputs
  73387. get: function () {
  73388. var gamepad = this.inputs.attached["gamepad"];
  73389. if (gamepad)
  73390. return gamepad.gamepadAngularSensibility;
  73391. return 0;
  73392. },
  73393. set: function (value) {
  73394. var gamepad = this.inputs.attached["gamepad"];
  73395. if (gamepad)
  73396. gamepad.gamepadAngularSensibility = value;
  73397. },
  73398. enumerable: true,
  73399. configurable: true
  73400. });
  73401. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73402. get: function () {
  73403. var gamepad = this.inputs.attached["gamepad"];
  73404. if (gamepad)
  73405. return gamepad.gamepadMoveSensibility;
  73406. return 0;
  73407. },
  73408. set: function (value) {
  73409. var gamepad = this.inputs.attached["gamepad"];
  73410. if (gamepad)
  73411. gamepad.gamepadMoveSensibility = value;
  73412. },
  73413. enumerable: true,
  73414. configurable: true
  73415. });
  73416. GamepadCamera.prototype.getClassName = function () {
  73417. return "GamepadCamera";
  73418. };
  73419. return GamepadCamera;
  73420. }(BABYLON.UniversalCamera));
  73421. BABYLON.GamepadCamera = GamepadCamera;
  73422. })(BABYLON || (BABYLON = {}));
  73423. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73424. var BABYLON;
  73425. (function (BABYLON) {
  73426. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73427. function PostProcessRenderPipelineManager() {
  73428. this._renderPipelines = {};
  73429. }
  73430. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73431. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73432. };
  73433. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73434. if (unique === void 0) { unique = false; }
  73435. var renderPipeline = this._renderPipelines[renderPipelineName];
  73436. if (!renderPipeline) {
  73437. return;
  73438. }
  73439. renderPipeline._attachCameras(cameras, unique);
  73440. };
  73441. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73442. var renderPipeline = this._renderPipelines[renderPipelineName];
  73443. if (!renderPipeline) {
  73444. return;
  73445. }
  73446. renderPipeline._detachCameras(cameras);
  73447. };
  73448. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73449. var renderPipeline = this._renderPipelines[renderPipelineName];
  73450. if (!renderPipeline) {
  73451. return;
  73452. }
  73453. renderPipeline._enableEffect(renderEffectName, cameras);
  73454. };
  73455. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73456. var renderPipeline = this._renderPipelines[renderPipelineName];
  73457. if (!renderPipeline) {
  73458. return;
  73459. }
  73460. renderPipeline._disableEffect(renderEffectName, cameras);
  73461. };
  73462. PostProcessRenderPipelineManager.prototype.update = function () {
  73463. for (var renderPipelineName in this._renderPipelines) {
  73464. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73465. var pipeline = this._renderPipelines[renderPipelineName];
  73466. if (!pipeline.isSupported) {
  73467. pipeline.dispose();
  73468. delete this._renderPipelines[renderPipelineName];
  73469. }
  73470. else {
  73471. pipeline._update();
  73472. }
  73473. }
  73474. }
  73475. };
  73476. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73477. for (var renderPipelineName in this._renderPipelines) {
  73478. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73479. var pipeline = this._renderPipelines[renderPipelineName];
  73480. pipeline._rebuild();
  73481. }
  73482. }
  73483. };
  73484. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73485. for (var renderPipelineName in this._renderPipelines) {
  73486. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73487. var pipeline = this._renderPipelines[renderPipelineName];
  73488. pipeline.dispose();
  73489. }
  73490. }
  73491. };
  73492. return PostProcessRenderPipelineManager;
  73493. }());
  73494. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73495. })(BABYLON || (BABYLON = {}));
  73496. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73497. var BABYLON;
  73498. (function (BABYLON) {
  73499. /**
  73500. * This represents a set of one or more post processes in Babylon.
  73501. * A post process can be used to apply a shader to a texture after it is rendered.
  73502. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73503. */
  73504. var PostProcessRenderEffect = /** @class */ (function () {
  73505. /**
  73506. * Instantiates a post process render effect.
  73507. * A post process can be used to apply a shader to a texture after it is rendered.
  73508. * @param engine The engine the effect is tied to
  73509. * @param name The name of the effect
  73510. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73511. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73512. */
  73513. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73514. this._name = name;
  73515. this._singleInstance = singleInstance || true;
  73516. this._getPostProcesses = getPostProcesses;
  73517. this._cameras = {};
  73518. this._indicesForCamera = {};
  73519. this._postProcesses = {};
  73520. }
  73521. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73522. /**
  73523. * Checks if all the post processes in the effect are supported.
  73524. */
  73525. get: function () {
  73526. for (var index in this._postProcesses) {
  73527. if (this._postProcesses.hasOwnProperty(index)) {
  73528. var pps = this._postProcesses[index];
  73529. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73530. if (!pps[ppIndex].isSupported) {
  73531. return false;
  73532. }
  73533. }
  73534. }
  73535. }
  73536. return true;
  73537. },
  73538. enumerable: true,
  73539. configurable: true
  73540. });
  73541. /**
  73542. * Updates the current state of the effect
  73543. */
  73544. PostProcessRenderEffect.prototype._update = function () {
  73545. };
  73546. /**
  73547. * Attaches the effect on cameras
  73548. * @param cameras The camera to attach to.
  73549. */
  73550. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73551. var _this = this;
  73552. var cameraKey;
  73553. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73554. if (!cams) {
  73555. return;
  73556. }
  73557. for (var i = 0; i < cams.length; i++) {
  73558. var camera = cams[i];
  73559. var cameraName = camera.name;
  73560. if (this._singleInstance) {
  73561. cameraKey = 0;
  73562. }
  73563. else {
  73564. cameraKey = cameraName;
  73565. }
  73566. if (!this._postProcesses[cameraKey]) {
  73567. var postProcess = this._getPostProcesses();
  73568. if (postProcess) {
  73569. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73570. }
  73571. }
  73572. if (!this._indicesForCamera[cameraName]) {
  73573. this._indicesForCamera[cameraName] = [];
  73574. }
  73575. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73576. var index = camera.attachPostProcess(postProcess);
  73577. _this._indicesForCamera[cameraName].push(index);
  73578. });
  73579. if (!this._cameras[cameraName]) {
  73580. this._cameras[cameraName] = camera;
  73581. }
  73582. }
  73583. };
  73584. /**
  73585. * Detatches the effect on cameras
  73586. * @param cameras The camera to detatch from.
  73587. */
  73588. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73589. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73590. if (!cams) {
  73591. return;
  73592. }
  73593. for (var i = 0; i < cams.length; i++) {
  73594. var camera = cams[i];
  73595. var cameraName = camera.name;
  73596. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73597. camera.detachPostProcess(postProcess);
  73598. });
  73599. if (this._cameras[cameraName]) {
  73600. //this._indicesForCamera.splice(index, 1);
  73601. this._cameras[cameraName] = null;
  73602. }
  73603. }
  73604. };
  73605. /**
  73606. * Enables the effect on given cameras
  73607. * @param cameras The camera to enable.
  73608. */
  73609. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73610. var _this = this;
  73611. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73612. if (!cams) {
  73613. return;
  73614. }
  73615. for (var i = 0; i < cams.length; i++) {
  73616. var camera = cams[i];
  73617. var cameraName = camera.name;
  73618. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73619. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73620. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73621. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73622. });
  73623. }
  73624. }
  73625. }
  73626. };
  73627. /**
  73628. * Disables the effect on the given cameras
  73629. * @param cameras The camera to disable.
  73630. */
  73631. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73632. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73633. if (!cams) {
  73634. return;
  73635. }
  73636. for (var i = 0; i < cams.length; i++) {
  73637. var camera = cams[i];
  73638. var cameraName = camera.name;
  73639. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73640. camera.detachPostProcess(postProcess);
  73641. });
  73642. }
  73643. };
  73644. /**
  73645. * Gets a list of the post processes contained in the effect.
  73646. * @param camera The camera to get the post processes on.
  73647. * @returns The list of the post processes in the effect.
  73648. */
  73649. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73650. if (this._singleInstance) {
  73651. return this._postProcesses[0];
  73652. }
  73653. else {
  73654. if (!camera) {
  73655. return null;
  73656. }
  73657. return this._postProcesses[camera.name];
  73658. }
  73659. };
  73660. return PostProcessRenderEffect;
  73661. }());
  73662. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73663. })(BABYLON || (BABYLON = {}));
  73664. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73665. var BABYLON;
  73666. (function (BABYLON) {
  73667. var PostProcessRenderPipeline = /** @class */ (function () {
  73668. function PostProcessRenderPipeline(engine, name) {
  73669. this.engine = engine;
  73670. this._name = name;
  73671. this._renderEffects = {};
  73672. this._renderEffectsForIsolatedPass = new Array();
  73673. this._cameras = [];
  73674. }
  73675. PostProcessRenderPipeline.prototype.getClassName = function () {
  73676. return "PostProcessRenderPipeline";
  73677. };
  73678. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73679. get: function () {
  73680. for (var renderEffectName in this._renderEffects) {
  73681. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73682. if (!this._renderEffects[renderEffectName].isSupported) {
  73683. return false;
  73684. }
  73685. }
  73686. }
  73687. return true;
  73688. },
  73689. enumerable: true,
  73690. configurable: true
  73691. });
  73692. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73693. this._renderEffects[renderEffect._name] = renderEffect;
  73694. };
  73695. // private
  73696. PostProcessRenderPipeline.prototype._rebuild = function () {
  73697. };
  73698. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73699. var renderEffects = this._renderEffects[renderEffectName];
  73700. if (!renderEffects) {
  73701. return;
  73702. }
  73703. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73704. };
  73705. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73706. var renderEffects = this._renderEffects[renderEffectName];
  73707. if (!renderEffects) {
  73708. return;
  73709. }
  73710. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73711. };
  73712. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73713. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73714. if (!cams) {
  73715. return;
  73716. }
  73717. var indicesToDelete = [];
  73718. var i;
  73719. for (i = 0; i < cams.length; i++) {
  73720. var camera = cams[i];
  73721. var cameraName = camera.name;
  73722. if (this._cameras.indexOf(camera) === -1) {
  73723. this._cameras[cameraName] = camera;
  73724. }
  73725. else if (unique) {
  73726. indicesToDelete.push(i);
  73727. }
  73728. }
  73729. for (i = 0; i < indicesToDelete.length; i++) {
  73730. cameras.splice(indicesToDelete[i], 1);
  73731. }
  73732. for (var renderEffectName in this._renderEffects) {
  73733. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73734. this._renderEffects[renderEffectName]._attachCameras(cams);
  73735. }
  73736. }
  73737. };
  73738. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73739. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73740. if (!cams) {
  73741. return;
  73742. }
  73743. for (var renderEffectName in this._renderEffects) {
  73744. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73745. this._renderEffects[renderEffectName]._detachCameras(cams);
  73746. }
  73747. }
  73748. for (var i = 0; i < cams.length; i++) {
  73749. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73750. }
  73751. };
  73752. PostProcessRenderPipeline.prototype._update = function () {
  73753. for (var renderEffectName in this._renderEffects) {
  73754. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73755. this._renderEffects[renderEffectName]._update();
  73756. }
  73757. }
  73758. for (var i = 0; i < this._cameras.length; i++) {
  73759. var cameraName = this._cameras[i].name;
  73760. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73761. this._renderEffectsForIsolatedPass[cameraName]._update();
  73762. }
  73763. }
  73764. };
  73765. PostProcessRenderPipeline.prototype._reset = function () {
  73766. this._renderEffects = {};
  73767. this._renderEffectsForIsolatedPass = new Array();
  73768. };
  73769. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73770. // 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)
  73771. var effectKeys = Object.keys(this._renderEffects);
  73772. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73773. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73774. if (postProcesses) {
  73775. postProcesses[0].samples = sampleCount;
  73776. return true;
  73777. }
  73778. }
  73779. return false;
  73780. };
  73781. PostProcessRenderPipeline.prototype.dispose = function () {
  73782. // Must be implemented by children
  73783. };
  73784. __decorate([
  73785. BABYLON.serialize()
  73786. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73787. return PostProcessRenderPipeline;
  73788. }());
  73789. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73790. })(BABYLON || (BABYLON = {}));
  73791. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73792. var BABYLON;
  73793. (function (BABYLON) {
  73794. /**
  73795. * This represents a depth renderer in Babylon.
  73796. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73797. */
  73798. var DepthRenderer = /** @class */ (function () {
  73799. /**
  73800. * Instantiates a depth renderer
  73801. * @param scene The scene the renderer belongs to
  73802. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73803. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73804. */
  73805. function DepthRenderer(scene, type, camera) {
  73806. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73807. if (camera === void 0) { camera = null; }
  73808. var _this = this;
  73809. this._scene = scene;
  73810. this._camera = camera;
  73811. var engine = scene.getEngine();
  73812. // Render target
  73813. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73814. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73815. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73816. this._depthMap.refreshRate = 1;
  73817. this._depthMap.renderParticles = false;
  73818. this._depthMap.renderList = null;
  73819. // Camera to get depth map from to support multiple concurrent cameras
  73820. this._depthMap.activeCamera = this._camera;
  73821. this._depthMap.ignoreCameraViewport = true;
  73822. this._depthMap.useCameraPostProcesses = false;
  73823. // set default depth value to 1.0 (far away)
  73824. this._depthMap.onClearObservable.add(function (engine) {
  73825. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73826. });
  73827. // Custom render function
  73828. var renderSubMesh = function (subMesh) {
  73829. var mesh = subMesh.getRenderingMesh();
  73830. var scene = _this._scene;
  73831. var engine = scene.getEngine();
  73832. var material = subMesh.getMaterial();
  73833. if (!material) {
  73834. return;
  73835. }
  73836. // Culling and reverse (right handed system)
  73837. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73838. // Managing instances
  73839. var batch = mesh._getInstancesRenderList(subMesh._id);
  73840. if (batch.mustReturn) {
  73841. return;
  73842. }
  73843. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73844. var camera = _this._camera || scene.activeCamera;
  73845. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73846. engine.enableEffect(_this._effect);
  73847. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73848. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73849. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73850. // Alpha test
  73851. if (material && material.needAlphaTesting()) {
  73852. var alphaTexture = material.getAlphaTestTexture();
  73853. if (alphaTexture) {
  73854. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73855. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73856. }
  73857. }
  73858. // Bones
  73859. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73860. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73861. }
  73862. // Draw
  73863. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73864. }
  73865. };
  73866. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73867. var index;
  73868. if (depthOnlySubMeshes.length) {
  73869. engine.setColorWrite(false);
  73870. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73871. renderSubMesh(depthOnlySubMeshes.data[index]);
  73872. }
  73873. engine.setColorWrite(true);
  73874. }
  73875. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73876. renderSubMesh(opaqueSubMeshes.data[index]);
  73877. }
  73878. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73879. renderSubMesh(alphaTestSubMeshes.data[index]);
  73880. }
  73881. };
  73882. }
  73883. /**
  73884. * Creates the depth rendering effect and checks if the effect is ready.
  73885. * @param subMesh The submesh to be used to render the depth map of
  73886. * @param useInstances If multiple world instances should be used
  73887. * @returns if the depth renderer is ready to render the depth map
  73888. */
  73889. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73890. var material = subMesh.getMaterial();
  73891. if (material.disableDepthWrite) {
  73892. return false;
  73893. }
  73894. var defines = [];
  73895. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73896. var mesh = subMesh.getMesh();
  73897. // Alpha test
  73898. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73899. defines.push("#define ALPHATEST");
  73900. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73901. attribs.push(BABYLON.VertexBuffer.UVKind);
  73902. defines.push("#define UV1");
  73903. }
  73904. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73905. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73906. defines.push("#define UV2");
  73907. }
  73908. }
  73909. // Bones
  73910. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73911. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73912. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73913. if (mesh.numBoneInfluencers > 4) {
  73914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73916. }
  73917. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73918. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73919. }
  73920. else {
  73921. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73922. }
  73923. // Instances
  73924. if (useInstances) {
  73925. defines.push("#define INSTANCES");
  73926. attribs.push("world0");
  73927. attribs.push("world1");
  73928. attribs.push("world2");
  73929. attribs.push("world3");
  73930. }
  73931. // Get correct effect
  73932. var join = defines.join("\n");
  73933. if (this._cachedDefines !== join) {
  73934. this._cachedDefines = join;
  73935. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73936. }
  73937. return this._effect.isReady();
  73938. };
  73939. /**
  73940. * Gets the texture which the depth map will be written to.
  73941. * @returns The depth map texture
  73942. */
  73943. DepthRenderer.prototype.getDepthMap = function () {
  73944. return this._depthMap;
  73945. };
  73946. /**
  73947. * Disposes of the depth renderer.
  73948. */
  73949. DepthRenderer.prototype.dispose = function () {
  73950. this._depthMap.dispose();
  73951. };
  73952. return DepthRenderer;
  73953. }());
  73954. BABYLON.DepthRenderer = DepthRenderer;
  73955. })(BABYLON || (BABYLON = {}));
  73956. //# sourceMappingURL=babylon.depthRenderer.js.map
  73957. var BABYLON;
  73958. (function (BABYLON) {
  73959. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73960. __extends(SSAORenderingPipeline, _super);
  73961. /**
  73962. * @constructor
  73963. * @param {string} name - The rendering pipeline name
  73964. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73965. * @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 }
  73966. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73967. */
  73968. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73969. var _this = _super.call(this, scene.getEngine(), name) || this;
  73970. // Members
  73971. /**
  73972. * The PassPostProcess id in the pipeline that contains the original scene color
  73973. */
  73974. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73975. /**
  73976. * The SSAO PostProcess id in the pipeline
  73977. */
  73978. _this.SSAORenderEffect = "SSAORenderEffect";
  73979. /**
  73980. * The horizontal blur PostProcess id in the pipeline
  73981. */
  73982. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73983. /**
  73984. * The vertical blur PostProcess id in the pipeline
  73985. */
  73986. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73987. /**
  73988. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73989. */
  73990. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73991. /**
  73992. * The output strength of the SSAO post-process. Default value is 1.0.
  73993. */
  73994. _this.totalStrength = 1.0;
  73995. /**
  73996. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73997. */
  73998. _this.radius = 0.0001;
  73999. /**
  74000. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  74001. * Must not be equal to fallOff and superior to fallOff.
  74002. * Default value is 0.975
  74003. */
  74004. _this.area = 0.0075;
  74005. /**
  74006. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  74007. * Must not be equal to area and inferior to area.
  74008. * Default value is 0.0
  74009. */
  74010. _this.fallOff = 0.000001;
  74011. /**
  74012. * The base color of the SSAO post-process
  74013. * The final result is "base + ssao" between [0, 1]
  74014. */
  74015. _this.base = 0.5;
  74016. _this._firstUpdate = true;
  74017. _this._scene = scene;
  74018. // Set up assets
  74019. _this._createRandomTexture();
  74020. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74021. var ssaoRatio = ratio.ssaoRatio || ratio;
  74022. var combineRatio = ratio.combineRatio || ratio;
  74023. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74024. _this._createSSAOPostProcess(ssaoRatio);
  74025. _this._createBlurPostProcess(ssaoRatio);
  74026. _this._createSSAOCombinePostProcess(combineRatio);
  74027. // Set up pipeline
  74028. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74029. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74030. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74031. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74032. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74033. // Finish
  74034. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74035. if (cameras)
  74036. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74037. return _this;
  74038. }
  74039. // Public Methods
  74040. /**
  74041. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74042. */
  74043. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74044. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74045. for (var i = 0; i < this._scene.cameras.length; i++) {
  74046. var camera = this._scene.cameras[i];
  74047. this._originalColorPostProcess.dispose(camera);
  74048. this._ssaoPostProcess.dispose(camera);
  74049. this._blurHPostProcess.dispose(camera);
  74050. this._blurVPostProcess.dispose(camera);
  74051. this._ssaoCombinePostProcess.dispose(camera);
  74052. }
  74053. this._randomTexture.dispose();
  74054. if (disableDepthRender)
  74055. this._scene.disableDepthRenderer();
  74056. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74057. _super.prototype.dispose.call(this);
  74058. };
  74059. // Private Methods
  74060. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  74061. var _this = this;
  74062. var size = 16;
  74063. 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);
  74064. 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);
  74065. this._blurHPostProcess.onActivateObservable.add(function () {
  74066. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  74067. _this._blurHPostProcess.kernel = size * dw;
  74068. });
  74069. this._blurVPostProcess.onActivateObservable.add(function () {
  74070. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  74071. _this._blurVPostProcess.kernel = size * dw;
  74072. });
  74073. };
  74074. SSAORenderingPipeline.prototype._rebuild = function () {
  74075. this._firstUpdate = true;
  74076. _super.prototype._rebuild.call(this);
  74077. };
  74078. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74079. var _this = this;
  74080. var numSamples = 16;
  74081. var sampleSphere = [
  74082. 0.5381, 0.1856, -0.4319,
  74083. 0.1379, 0.2486, 0.4430,
  74084. 0.3371, 0.5679, -0.0057,
  74085. -0.6999, -0.0451, -0.0019,
  74086. 0.0689, -0.1598, -0.8547,
  74087. 0.0560, 0.0069, -0.1843,
  74088. -0.0146, 0.1402, 0.0762,
  74089. 0.0100, -0.1924, -0.0344,
  74090. -0.3577, -0.5301, -0.4358,
  74091. -0.3169, 0.1063, 0.0158,
  74092. 0.0103, -0.5869, 0.0046,
  74093. -0.0897, -0.4940, 0.3287,
  74094. 0.7119, -0.0154, -0.0918,
  74095. -0.0533, 0.0596, -0.5411,
  74096. 0.0352, -0.0631, 0.5460,
  74097. -0.4776, 0.2847, -0.0271
  74098. ];
  74099. var samplesFactor = 1.0 / numSamples;
  74100. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  74101. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74102. "area", "fallOff", "base", "range", "viewport"
  74103. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74104. this._ssaoPostProcess.onApply = function (effect) {
  74105. if (_this._firstUpdate) {
  74106. effect.setArray3("sampleSphere", sampleSphere);
  74107. effect.setFloat("samplesFactor", samplesFactor);
  74108. effect.setFloat("randTextureTiles", 4.0);
  74109. }
  74110. effect.setFloat("totalStrength", _this.totalStrength);
  74111. effect.setFloat("radius", _this.radius);
  74112. effect.setFloat("area", _this.area);
  74113. effect.setFloat("fallOff", _this.fallOff);
  74114. effect.setFloat("base", _this.base);
  74115. effect.setTexture("textureSampler", _this._depthTexture);
  74116. effect.setTexture("randomSampler", _this._randomTexture);
  74117. };
  74118. };
  74119. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74120. var _this = this;
  74121. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74122. this._ssaoCombinePostProcess.onApply = function (effect) {
  74123. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  74124. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74125. };
  74126. };
  74127. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  74128. var size = 512;
  74129. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74130. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74131. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74132. var context = this._randomTexture.getContext();
  74133. var rand = function (min, max) {
  74134. return Math.random() * (max - min) + min;
  74135. };
  74136. var randVector = BABYLON.Vector3.Zero();
  74137. for (var x = 0; x < size; x++) {
  74138. for (var y = 0; y < size; y++) {
  74139. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  74140. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  74141. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  74142. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74143. context.fillRect(x, y, 1, 1);
  74144. }
  74145. }
  74146. this._randomTexture.update(false);
  74147. };
  74148. __decorate([
  74149. BABYLON.serialize()
  74150. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  74151. __decorate([
  74152. BABYLON.serialize()
  74153. ], SSAORenderingPipeline.prototype, "radius", void 0);
  74154. __decorate([
  74155. BABYLON.serialize()
  74156. ], SSAORenderingPipeline.prototype, "area", void 0);
  74157. __decorate([
  74158. BABYLON.serialize()
  74159. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74160. __decorate([
  74161. BABYLON.serialize()
  74162. ], SSAORenderingPipeline.prototype, "base", void 0);
  74163. return SSAORenderingPipeline;
  74164. }(BABYLON.PostProcessRenderPipeline));
  74165. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74166. })(BABYLON || (BABYLON = {}));
  74167. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74168. var BABYLON;
  74169. (function (BABYLON) {
  74170. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74171. __extends(SSAO2RenderingPipeline, _super);
  74172. /**
  74173. * @constructor
  74174. * @param {string} name - The rendering pipeline name
  74175. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74176. * @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 }
  74177. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74178. */
  74179. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74180. var _this = _super.call(this, scene.getEngine(), name) || this;
  74181. // Members
  74182. /**
  74183. * The PassPostProcess id in the pipeline that contains the original scene color
  74184. */
  74185. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74186. /**
  74187. * The SSAO PostProcess id in the pipeline
  74188. */
  74189. _this.SSAORenderEffect = "SSAORenderEffect";
  74190. /**
  74191. * The horizontal blur PostProcess id in the pipeline
  74192. */
  74193. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74194. /**
  74195. * The vertical blur PostProcess id in the pipeline
  74196. */
  74197. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74198. /**
  74199. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74200. */
  74201. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74202. /**
  74203. * The output strength of the SSAO post-process. Default value is 1.0.
  74204. */
  74205. _this.totalStrength = 1.0;
  74206. /**
  74207. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74208. */
  74209. _this.maxZ = 100.0;
  74210. /**
  74211. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74212. */
  74213. _this.minZAspect = 0.2;
  74214. /**
  74215. * Number of samples used for the SSAO calculations. Default value is 8
  74216. */
  74217. _this._samples = 8;
  74218. /**
  74219. * Are we using bilateral blur ?
  74220. */
  74221. _this._expensiveBlur = true;
  74222. /**
  74223. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74224. */
  74225. _this.radius = 2.0;
  74226. /**
  74227. * The base color of the SSAO post-process
  74228. * The final result is "base + ssao" between [0, 1]
  74229. */
  74230. _this.base = 0.1;
  74231. _this._firstUpdate = true;
  74232. _this._scene = scene;
  74233. _this._ratio = ratio;
  74234. if (!_this.isSupported) {
  74235. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74236. return _this;
  74237. }
  74238. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74239. var blurRatio = _this._ratio.blurRatio || ratio;
  74240. // Set up assets
  74241. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74242. _this._createRandomTexture();
  74243. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74244. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74245. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74246. _this._createSSAOPostProcess(1.0);
  74247. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74248. _this._createSSAOCombinePostProcess(blurRatio);
  74249. // Set up pipeline
  74250. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74251. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74253. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74254. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74255. // Finish
  74256. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74257. if (cameras)
  74258. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74259. return _this;
  74260. }
  74261. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74262. get: function () {
  74263. return this._samples;
  74264. },
  74265. set: function (n) {
  74266. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74267. this._samples = n;
  74268. this._sampleSphere = this._generateHemisphere();
  74269. this._firstUpdate = true;
  74270. },
  74271. enumerable: true,
  74272. configurable: true
  74273. });
  74274. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74275. get: function () {
  74276. return this._expensiveBlur;
  74277. },
  74278. set: function (b) {
  74279. 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"]);
  74280. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74281. this._expensiveBlur = b;
  74282. this._firstUpdate = true;
  74283. },
  74284. enumerable: true,
  74285. configurable: true
  74286. });
  74287. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74288. /**
  74289. * Support test.
  74290. */
  74291. get: function () {
  74292. var engine = BABYLON.Engine.LastCreatedEngine;
  74293. if (!engine) {
  74294. return false;
  74295. }
  74296. return engine.getCaps().drawBuffersExtension;
  74297. },
  74298. enumerable: true,
  74299. configurable: true
  74300. });
  74301. // Public Methods
  74302. /**
  74303. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74304. */
  74305. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74306. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74307. for (var i = 0; i < this._scene.cameras.length; i++) {
  74308. var camera = this._scene.cameras[i];
  74309. this._originalColorPostProcess.dispose(camera);
  74310. this._ssaoPostProcess.dispose(camera);
  74311. this._blurHPostProcess.dispose(camera);
  74312. this._blurVPostProcess.dispose(camera);
  74313. this._ssaoCombinePostProcess.dispose(camera);
  74314. }
  74315. this._randomTexture.dispose();
  74316. if (disableGeometryBufferRenderer)
  74317. this._scene.disableGeometryBufferRenderer();
  74318. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74319. _super.prototype.dispose.call(this);
  74320. };
  74321. // Private Methods
  74322. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74323. var _this = this;
  74324. this._samplerOffsets = [];
  74325. var expensive = this.expensiveBlur;
  74326. for (var i = -8; i < 8; i++) {
  74327. this._samplerOffsets.push(i * 2 + 0.5);
  74328. }
  74329. 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");
  74330. this._blurHPostProcess.onApply = function (effect) {
  74331. if (!_this._scene.activeCamera) {
  74332. return;
  74333. }
  74334. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74335. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74336. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74337. effect.setFloat("radius", _this.radius);
  74338. effect.setTexture("depthSampler", _this._depthTexture);
  74339. if (_this._firstUpdate) {
  74340. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74341. }
  74342. };
  74343. 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");
  74344. this._blurVPostProcess.onApply = function (effect) {
  74345. if (!_this._scene.activeCamera) {
  74346. return;
  74347. }
  74348. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74349. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74350. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74351. effect.setFloat("radius", _this.radius);
  74352. effect.setTexture("depthSampler", _this._depthTexture);
  74353. if (_this._firstUpdate) {
  74354. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74355. _this._firstUpdate = false;
  74356. }
  74357. };
  74358. };
  74359. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74360. this._firstUpdate = true;
  74361. _super.prototype._rebuild.call(this);
  74362. };
  74363. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74364. var numSamples = this.samples;
  74365. var result = [];
  74366. var vector, scale;
  74367. var rand = function (min, max) {
  74368. return Math.random() * (max - min) + min;
  74369. };
  74370. var i = 0;
  74371. while (i < numSamples) {
  74372. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74373. vector.normalize();
  74374. scale = i / numSamples;
  74375. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74376. vector.scaleInPlace(scale);
  74377. result.push(vector.x, vector.y, vector.z);
  74378. i++;
  74379. }
  74380. return result;
  74381. };
  74382. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74383. var _this = this;
  74384. var numSamples = this.samples;
  74385. this._sampleSphere = this._generateHemisphere();
  74386. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74387. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74388. "base", "range", "projection", "near", "far", "texelSize",
  74389. "xViewport", "yViewport", "maxZ", "minZAspect"
  74390. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74391. this._ssaoPostProcess.onApply = function (effect) {
  74392. if (_this._firstUpdate) {
  74393. effect.setArray3("sampleSphere", _this._sampleSphere);
  74394. effect.setFloat("randTextureTiles", 4.0);
  74395. }
  74396. if (!_this._scene.activeCamera) {
  74397. return;
  74398. }
  74399. effect.setFloat("samplesFactor", 1 / _this.samples);
  74400. effect.setFloat("totalStrength", _this.totalStrength);
  74401. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74402. effect.setFloat("radius", _this.radius);
  74403. effect.setFloat("maxZ", _this.maxZ);
  74404. effect.setFloat("minZAspect", _this.minZAspect);
  74405. effect.setFloat("base", _this.base);
  74406. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74407. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74408. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74409. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74410. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74411. effect.setTexture("textureSampler", _this._depthTexture);
  74412. effect.setTexture("normalSampler", _this._normalTexture);
  74413. effect.setTexture("randomSampler", _this._randomTexture);
  74414. };
  74415. };
  74416. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74417. var _this = this;
  74418. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74419. this._ssaoCombinePostProcess.onApply = function (effect) {
  74420. var viewport = _this._scene.activeCamera.viewport;
  74421. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74422. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74423. };
  74424. };
  74425. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74426. var size = 512;
  74427. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74428. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74429. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74430. var context = this._randomTexture.getContext();
  74431. var rand = function (min, max) {
  74432. return Math.random() * (max - min) + min;
  74433. };
  74434. var randVector = BABYLON.Vector3.Zero();
  74435. for (var x = 0; x < size; x++) {
  74436. for (var y = 0; y < size; y++) {
  74437. randVector.x = rand(0.0, 1.0);
  74438. randVector.y = rand(0.0, 1.0);
  74439. randVector.z = 0.0;
  74440. randVector.normalize();
  74441. randVector.scaleInPlace(255);
  74442. randVector.x = Math.floor(randVector.x);
  74443. randVector.y = Math.floor(randVector.y);
  74444. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74445. context.fillRect(x, y, 1, 1);
  74446. }
  74447. }
  74448. this._randomTexture.update(false);
  74449. };
  74450. /**
  74451. * Serialize the rendering pipeline (Used when exporting)
  74452. * @returns the serialized object
  74453. */
  74454. SSAO2RenderingPipeline.prototype.serialize = function () {
  74455. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74456. serializationObject.customType = "SSAO2RenderingPipeline";
  74457. return serializationObject;
  74458. };
  74459. /**
  74460. * Parse the serialized pipeline
  74461. * @param source Source pipeline.
  74462. * @param scene The scene to load the pipeline to.
  74463. * @param rootUrl The URL of the serialized pipeline.
  74464. * @returns An instantiated pipeline from the serialized object.
  74465. */
  74466. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74467. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74468. };
  74469. __decorate([
  74470. BABYLON.serialize()
  74471. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74472. __decorate([
  74473. BABYLON.serialize()
  74474. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74475. __decorate([
  74476. BABYLON.serialize()
  74477. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74478. __decorate([
  74479. BABYLON.serialize("samples")
  74480. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74481. __decorate([
  74482. BABYLON.serialize()
  74483. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74484. __decorate([
  74485. BABYLON.serialize("expensiveBlur")
  74486. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74487. __decorate([
  74488. BABYLON.serialize()
  74489. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74490. __decorate([
  74491. BABYLON.serialize()
  74492. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74493. return SSAO2RenderingPipeline;
  74494. }(BABYLON.PostProcessRenderPipeline));
  74495. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74496. })(BABYLON || (BABYLON = {}));
  74497. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74498. // BABYLON.JS Chromatic Aberration GLSL Shader
  74499. // Author: Olivier Guyot
  74500. // Separates very slightly R, G and B colors on the edges of the screen
  74501. // Inspired by Francois Tarlier & Martins Upitis
  74502. var BABYLON;
  74503. (function (BABYLON) {
  74504. var LensRenderingPipeline = /** @class */ (function (_super) {
  74505. __extends(LensRenderingPipeline, _super);
  74506. /**
  74507. * @constructor
  74508. *
  74509. * Effect parameters are as follow:
  74510. * {
  74511. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74512. * edge_blur: number; // from 0 to x (1 for realism)
  74513. * distortion: number; // from 0 to x (1 for realism)
  74514. * grain_amount: number; // from 0 to 1
  74515. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74516. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74517. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74518. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74519. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74520. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74521. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74522. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74523. * }
  74524. * Note: if an effect parameter is unset, effect is disabled
  74525. *
  74526. * @param {string} name - The rendering pipeline name
  74527. * @param {object} parameters - An object containing all parameters (see above)
  74528. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74529. * @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)
  74530. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74531. */
  74532. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74533. if (ratio === void 0) { ratio = 1.0; }
  74534. var _this = _super.call(this, scene.getEngine(), name) || this;
  74535. // Lens effects can be of the following:
  74536. // - chromatic aberration (slight shift of RGB colors)
  74537. // - blur on the edge of the lens
  74538. // - lens distortion
  74539. // - depth-of-field blur & highlights enhancing
  74540. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74541. // - grain effect (noise or custom texture)
  74542. // Two additional texture samplers are needed:
  74543. // - depth map (for depth-of-field)
  74544. // - grain texture
  74545. /**
  74546. * The chromatic aberration PostProcess id in the pipeline
  74547. */
  74548. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74549. /**
  74550. * The highlights enhancing PostProcess id in the pipeline
  74551. */
  74552. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74553. /**
  74554. * The depth-of-field PostProcess id in the pipeline
  74555. */
  74556. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74557. _this._scene = scene;
  74558. // Fetch texture samplers
  74559. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74560. if (parameters.grain_texture) {
  74561. _this._grainTexture = parameters.grain_texture;
  74562. }
  74563. else {
  74564. _this._createGrainTexture();
  74565. }
  74566. // save parameters
  74567. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74568. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74569. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74570. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74571. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74572. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74573. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74574. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74575. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74576. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74577. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74578. // Create effects
  74579. _this._createChromaticAberrationPostProcess(ratio);
  74580. _this._createHighlightsPostProcess(ratio);
  74581. _this._createDepthOfFieldPostProcess(ratio / 4);
  74582. // Set up pipeline
  74583. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74584. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74585. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74586. if (_this._highlightsGain === -1) {
  74587. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74588. }
  74589. // Finish
  74590. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74591. if (cameras) {
  74592. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74593. }
  74594. return _this;
  74595. }
  74596. // public methods (self explanatory)
  74597. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74598. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74599. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74600. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74601. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74602. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74603. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74604. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74605. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74606. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74607. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74608. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74609. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74610. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74611. };
  74612. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74613. this._highlightsPostProcess.updateEffect();
  74614. };
  74615. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74616. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74617. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74618. this._highlightsGain = amount;
  74619. };
  74620. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74621. if (this._highlightsGain === -1) {
  74622. this._highlightsGain = 1.0;
  74623. }
  74624. this._highlightsThreshold = amount;
  74625. };
  74626. LensRenderingPipeline.prototype.disableHighlights = function () {
  74627. this._highlightsGain = -1;
  74628. };
  74629. /**
  74630. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74631. */
  74632. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74633. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74634. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74635. this._chromaticAberrationPostProcess = null;
  74636. this._highlightsPostProcess = null;
  74637. this._depthOfFieldPostProcess = null;
  74638. this._grainTexture.dispose();
  74639. if (disableDepthRender)
  74640. this._scene.disableDepthRenderer();
  74641. };
  74642. // colors shifting and distortion
  74643. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74644. var _this = this;
  74645. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74646. [], // samplers
  74647. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74648. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74649. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74650. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74651. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74652. effect.setFloat('radialIntensity', 1);
  74653. effect.setFloat2('direction', 17, 17);
  74654. effect.setFloat2('centerPosition', 0.5, 0.5);
  74655. };
  74656. };
  74657. // highlights enhancing
  74658. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74659. var _this = this;
  74660. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74661. [], // samplers
  74662. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74663. this._highlightsPostProcess.onApply = function (effect) {
  74664. effect.setFloat('gain', _this._highlightsGain);
  74665. effect.setFloat('threshold', _this._highlightsThreshold);
  74666. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74667. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74668. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74669. };
  74670. };
  74671. // colors shifting and distortion
  74672. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74673. var _this = this;
  74674. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74675. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74676. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74677. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74678. this._depthOfFieldPostProcess.onApply = function (effect) {
  74679. effect.setTexture("depthSampler", _this._depthTexture);
  74680. effect.setTexture("grainSampler", _this._grainTexture);
  74681. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74682. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74683. effect.setFloat('grain_amount', _this._grainAmount);
  74684. effect.setBool('blur_noise', _this._blurNoise);
  74685. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74686. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74687. effect.setFloat('distortion', _this._distortion);
  74688. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74689. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74690. effect.setFloat('aperture', _this._dofAperture);
  74691. effect.setFloat('darken', _this._dofDarken);
  74692. effect.setFloat('edge_blur', _this._edgeBlur);
  74693. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74694. if (_this._scene.activeCamera) {
  74695. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74696. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74697. }
  74698. };
  74699. };
  74700. // creates a black and white random noise texture, 512x512
  74701. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74702. var size = 512;
  74703. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74704. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74705. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74706. var context = this._grainTexture.getContext();
  74707. var rand = function (min, max) {
  74708. return Math.random() * (max - min) + min;
  74709. };
  74710. var value;
  74711. for (var x = 0; x < size; x++) {
  74712. for (var y = 0; y < size; y++) {
  74713. value = Math.floor(rand(0.42, 0.58) * 255);
  74714. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74715. context.fillRect(x, y, 1, 1);
  74716. }
  74717. }
  74718. this._grainTexture.update(false);
  74719. };
  74720. return LensRenderingPipeline;
  74721. }(BABYLON.PostProcessRenderPipeline));
  74722. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74723. })(BABYLON || (BABYLON = {}));
  74724. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74725. var BABYLON;
  74726. (function (BABYLON) {
  74727. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74728. __extends(StandardRenderingPipeline, _super);
  74729. /**
  74730. * @constructor
  74731. * @param {string} name - The rendering pipeline name
  74732. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74733. * @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)
  74734. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74735. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74736. */
  74737. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74738. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74739. var _this = _super.call(this, scene.getEngine(), name) || this;
  74740. _this.downSampleX4PostProcess = null;
  74741. _this.brightPassPostProcess = null;
  74742. _this.blurHPostProcesses = [];
  74743. _this.blurVPostProcesses = [];
  74744. _this.textureAdderPostProcess = null;
  74745. _this.volumetricLightPostProcess = null;
  74746. _this.volumetricLightSmoothXPostProcess = null;
  74747. _this.volumetricLightSmoothYPostProcess = null;
  74748. _this.volumetricLightMergePostProces = null;
  74749. _this.volumetricLightFinalPostProcess = null;
  74750. _this.luminancePostProcess = null;
  74751. _this.luminanceDownSamplePostProcesses = [];
  74752. _this.hdrPostProcess = null;
  74753. _this.textureAdderFinalPostProcess = null;
  74754. _this.lensFlareFinalPostProcess = null;
  74755. _this.hdrFinalPostProcess = null;
  74756. _this.lensFlarePostProcess = null;
  74757. _this.lensFlareComposePostProcess = null;
  74758. _this.motionBlurPostProcess = null;
  74759. _this.depthOfFieldPostProcess = null;
  74760. // Values
  74761. _this.brightThreshold = 1.0;
  74762. _this.blurWidth = 512.0;
  74763. _this.horizontalBlur = false;
  74764. _this.exposure = 1.0;
  74765. _this.lensTexture = null;
  74766. _this.volumetricLightCoefficient = 0.2;
  74767. _this.volumetricLightPower = 4.0;
  74768. _this.volumetricLightBlurScale = 64.0;
  74769. _this.sourceLight = null;
  74770. _this.hdrMinimumLuminance = 1.0;
  74771. _this.hdrDecreaseRate = 0.5;
  74772. _this.hdrIncreaseRate = 0.5;
  74773. _this.lensColorTexture = null;
  74774. _this.lensFlareStrength = 20.0;
  74775. _this.lensFlareGhostDispersal = 1.4;
  74776. _this.lensFlareHaloWidth = 0.7;
  74777. _this.lensFlareDistortionStrength = 16.0;
  74778. _this.lensStarTexture = null;
  74779. _this.lensFlareDirtTexture = null;
  74780. _this.depthOfFieldDistance = 10.0;
  74781. _this.depthOfFieldBlurWidth = 64.0;
  74782. _this.motionStrength = 1.0;
  74783. // IAnimatable
  74784. _this.animations = [];
  74785. _this._currentDepthOfFieldSource = null;
  74786. _this._hdrCurrentLuminance = 1.0;
  74787. // Getters and setters
  74788. _this._bloomEnabled = true;
  74789. _this._depthOfFieldEnabled = false;
  74790. _this._vlsEnabled = false;
  74791. _this._lensFlareEnabled = false;
  74792. _this._hdrEnabled = false;
  74793. _this._motionBlurEnabled = false;
  74794. _this._motionBlurSamples = 64.0;
  74795. _this._volumetricLightStepsCount = 50.0;
  74796. _this._cameras = cameras || [];
  74797. // Initialize
  74798. _this._scene = scene;
  74799. _this._basePostProcess = originalPostProcess;
  74800. _this._ratio = ratio;
  74801. // Misc
  74802. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74803. // Finish
  74804. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74805. _this._buildPipeline();
  74806. return _this;
  74807. }
  74808. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74809. get: function () {
  74810. return this._bloomEnabled;
  74811. },
  74812. set: function (enabled) {
  74813. if (this._bloomEnabled === enabled) {
  74814. return;
  74815. }
  74816. this._bloomEnabled = enabled;
  74817. this._buildPipeline();
  74818. },
  74819. enumerable: true,
  74820. configurable: true
  74821. });
  74822. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74823. get: function () {
  74824. return this._depthOfFieldEnabled;
  74825. },
  74826. set: function (enabled) {
  74827. if (this._depthOfFieldEnabled === enabled) {
  74828. return;
  74829. }
  74830. this._depthOfFieldEnabled = enabled;
  74831. this._buildPipeline();
  74832. },
  74833. enumerable: true,
  74834. configurable: true
  74835. });
  74836. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74837. get: function () {
  74838. return this._lensFlareEnabled;
  74839. },
  74840. set: function (enabled) {
  74841. if (this._lensFlareEnabled === enabled) {
  74842. return;
  74843. }
  74844. this._lensFlareEnabled = enabled;
  74845. this._buildPipeline();
  74846. },
  74847. enumerable: true,
  74848. configurable: true
  74849. });
  74850. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74851. get: function () {
  74852. return this._hdrEnabled;
  74853. },
  74854. set: function (enabled) {
  74855. if (this._hdrEnabled === enabled) {
  74856. return;
  74857. }
  74858. this._hdrEnabled = enabled;
  74859. this._buildPipeline();
  74860. },
  74861. enumerable: true,
  74862. configurable: true
  74863. });
  74864. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74865. get: function () {
  74866. return this._vlsEnabled;
  74867. },
  74868. set: function (enabled) {
  74869. if (this._vlsEnabled === enabled) {
  74870. return;
  74871. }
  74872. if (enabled) {
  74873. var geometry = this._scene.enableGeometryBufferRenderer();
  74874. if (!geometry) {
  74875. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74876. return;
  74877. }
  74878. }
  74879. this._vlsEnabled = enabled;
  74880. this._buildPipeline();
  74881. },
  74882. enumerable: true,
  74883. configurable: true
  74884. });
  74885. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74886. get: function () {
  74887. return this._motionBlurEnabled;
  74888. },
  74889. set: function (enabled) {
  74890. if (this._motionBlurEnabled === enabled) {
  74891. return;
  74892. }
  74893. this._motionBlurEnabled = enabled;
  74894. this._buildPipeline();
  74895. },
  74896. enumerable: true,
  74897. configurable: true
  74898. });
  74899. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74900. get: function () {
  74901. return this._volumetricLightStepsCount;
  74902. },
  74903. set: function (count) {
  74904. if (this.volumetricLightPostProcess) {
  74905. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74906. }
  74907. this._volumetricLightStepsCount = count;
  74908. },
  74909. enumerable: true,
  74910. configurable: true
  74911. });
  74912. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74913. get: function () {
  74914. return this._motionBlurSamples;
  74915. },
  74916. set: function (samples) {
  74917. if (this.motionBlurPostProcess) {
  74918. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74919. }
  74920. this._motionBlurSamples = samples;
  74921. },
  74922. enumerable: true,
  74923. configurable: true
  74924. });
  74925. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74926. var _this = this;
  74927. var ratio = this._ratio;
  74928. var scene = this._scene;
  74929. this._disposePostProcesses();
  74930. this._reset();
  74931. // Create pass post-process
  74932. if (!this._basePostProcess) {
  74933. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74934. this.originalPostProcess.onApply = function (effect) {
  74935. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74936. };
  74937. }
  74938. else {
  74939. this.originalPostProcess = this._basePostProcess;
  74940. }
  74941. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74942. this._currentDepthOfFieldSource = this.originalPostProcess;
  74943. if (this._bloomEnabled) {
  74944. // Create down sample X4 post-process
  74945. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74946. // Create bright pass post-process
  74947. this._createBrightPassPostProcess(scene, ratio / 2);
  74948. // Create gaussian blur post-processes (down sampling blurs)
  74949. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74950. // Create texture adder post-process
  74951. this._createTextureAdderPostProcess(scene, ratio);
  74952. // Create depth-of-field source post-process
  74953. 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);
  74954. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74955. }
  74956. if (this._vlsEnabled) {
  74957. // Create volumetric light
  74958. this._createVolumetricLightPostProcess(scene, ratio);
  74959. // Create volumetric light final post-process
  74960. 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);
  74961. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74962. }
  74963. if (this._lensFlareEnabled) {
  74964. // Create lens flare post-process
  74965. this._createLensFlarePostProcess(scene, ratio);
  74966. // Create depth-of-field source post-process post lens-flare and disable it now
  74967. 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);
  74968. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74969. }
  74970. if (this._hdrEnabled) {
  74971. // Create luminance
  74972. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74973. // Create HDR
  74974. this._createHdrPostProcess(scene, ratio);
  74975. // Create depth-of-field source post-process post hdr and disable it now
  74976. 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);
  74977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74978. }
  74979. if (this._depthOfFieldEnabled) {
  74980. // Create gaussian blur used by depth-of-field
  74981. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74982. // Create depth-of-field post-process
  74983. this._createDepthOfFieldPostProcess(scene, ratio);
  74984. }
  74985. if (this._motionBlurEnabled) {
  74986. // Create motion blur post-process
  74987. this._createMotionBlurPostProcess(scene, ratio);
  74988. }
  74989. if (this._cameras !== null) {
  74990. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74991. }
  74992. };
  74993. // Down Sample X4 Post-Processs
  74994. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74995. var _this = this;
  74996. var downSampleX4Offsets = new Array(32);
  74997. 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);
  74998. this.downSampleX4PostProcess.onApply = function (effect) {
  74999. var id = 0;
  75000. var width = _this.downSampleX4PostProcess.width;
  75001. var height = _this.downSampleX4PostProcess.height;
  75002. for (var i = -2; i < 2; i++) {
  75003. for (var j = -2; j < 2; j++) {
  75004. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  75005. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  75006. id += 2;
  75007. }
  75008. }
  75009. effect.setArray2("dsOffsets", downSampleX4Offsets);
  75010. };
  75011. // Add to pipeline
  75012. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  75013. };
  75014. // Brightpass Post-Process
  75015. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  75016. var _this = this;
  75017. var brightOffsets = new Array(8);
  75018. 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);
  75019. this.brightPassPostProcess.onApply = function (effect) {
  75020. var sU = (1.0 / _this.brightPassPostProcess.width);
  75021. var sV = (1.0 / _this.brightPassPostProcess.height);
  75022. brightOffsets[0] = -0.5 * sU;
  75023. brightOffsets[1] = 0.5 * sV;
  75024. brightOffsets[2] = 0.5 * sU;
  75025. brightOffsets[3] = 0.5 * sV;
  75026. brightOffsets[4] = -0.5 * sU;
  75027. brightOffsets[5] = -0.5 * sV;
  75028. brightOffsets[6] = 0.5 * sU;
  75029. brightOffsets[7] = -0.5 * sV;
  75030. effect.setArray2("dsOffsets", brightOffsets);
  75031. effect.setFloat("brightThreshold", _this.brightThreshold);
  75032. };
  75033. // Add to pipeline
  75034. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  75035. };
  75036. // Create blur H&V post-processes
  75037. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  75038. var _this = this;
  75039. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  75040. var engine = scene.getEngine();
  75041. 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);
  75042. 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);
  75043. blurX.onActivateObservable.add(function () {
  75044. var dw = blurX.width / engine.getRenderWidth();
  75045. blurX.kernel = _this[blurWidthKey] * dw;
  75046. });
  75047. blurY.onActivateObservable.add(function () {
  75048. var dw = blurY.height / engine.getRenderHeight();
  75049. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  75050. });
  75051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  75052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  75053. this.blurHPostProcesses.push(blurX);
  75054. this.blurVPostProcesses.push(blurY);
  75055. };
  75056. // Create texture adder post-process
  75057. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  75058. var _this = this;
  75059. 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);
  75060. this.textureAdderPostProcess.onApply = function (effect) {
  75061. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  75062. effect.setTexture("lensSampler", _this.lensTexture);
  75063. effect.setFloat("exposure", _this.exposure);
  75064. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  75065. };
  75066. // Add to pipeline
  75067. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  75068. };
  75069. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  75070. var _this = this;
  75071. var geometryRenderer = scene.enableGeometryBufferRenderer();
  75072. geometryRenderer.enablePosition = true;
  75073. var geometry = geometryRenderer.getGBuffer();
  75074. // Base post-process
  75075. 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));
  75076. var depthValues = BABYLON.Vector2.Zero();
  75077. this.volumetricLightPostProcess.onApply = function (effect) {
  75078. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  75079. var generator = _this.sourceLight.getShadowGenerator();
  75080. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  75081. effect.setTexture("positionSampler", geometry.textures[2]);
  75082. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  75083. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  75084. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  75085. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  75086. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  75087. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  75088. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  75089. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  75090. effect.setVector2("depthValues", depthValues);
  75091. }
  75092. };
  75093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  75094. // Smooth
  75095. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  75096. // Merge
  75097. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  75098. this.volumetricLightMergePostProces.onApply = function (effect) {
  75099. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  75100. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  75101. };
  75102. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  75103. };
  75104. // Create luminance
  75105. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  75106. var _this = this;
  75107. // Create luminance
  75108. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  75109. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  75110. var offsets = [];
  75111. this.luminancePostProcess.onApply = function (effect) {
  75112. var sU = (1.0 / _this.luminancePostProcess.width);
  75113. var sV = (1.0 / _this.luminancePostProcess.height);
  75114. offsets[0] = -0.5 * sU;
  75115. offsets[1] = 0.5 * sV;
  75116. offsets[2] = 0.5 * sU;
  75117. offsets[3] = 0.5 * sV;
  75118. offsets[4] = -0.5 * sU;
  75119. offsets[5] = -0.5 * sV;
  75120. offsets[6] = 0.5 * sU;
  75121. offsets[7] = -0.5 * sV;
  75122. effect.setArray2("lumOffsets", offsets);
  75123. };
  75124. // Add to pipeline
  75125. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  75126. // Create down sample luminance
  75127. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  75128. var size = Math.pow(3, i);
  75129. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  75130. if (i === 0) {
  75131. defines += "#define FINAL_DOWN_SAMPLER";
  75132. }
  75133. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  75134. this.luminanceDownSamplePostProcesses.push(postProcess);
  75135. }
  75136. // Create callbacks and add effects
  75137. var lastLuminance = this.luminancePostProcess;
  75138. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  75139. var downSampleOffsets = new Array(18);
  75140. pp.onApply = function (effect) {
  75141. if (!lastLuminance) {
  75142. return;
  75143. }
  75144. var id = 0;
  75145. for (var x = -1; x < 2; x++) {
  75146. for (var y = -1; y < 2; y++) {
  75147. downSampleOffsets[id] = x / lastLuminance.width;
  75148. downSampleOffsets[id + 1] = y / lastLuminance.height;
  75149. id += 2;
  75150. }
  75151. }
  75152. effect.setArray2("dsOffsets", downSampleOffsets);
  75153. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  75154. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75155. lastLuminance = _this.luminancePostProcess;
  75156. }
  75157. else {
  75158. lastLuminance = pp;
  75159. }
  75160. };
  75161. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75162. pp.onAfterRender = function (effect) {
  75163. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75164. 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);
  75165. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75166. };
  75167. }
  75168. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75169. });
  75170. };
  75171. // Create HDR post-process
  75172. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75173. var _this = this;
  75174. 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);
  75175. var outputLiminance = 1;
  75176. var time = 0;
  75177. var lastTime = 0;
  75178. this.hdrPostProcess.onApply = function (effect) {
  75179. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75180. time += scene.getEngine().getDeltaTime();
  75181. if (outputLiminance < 0) {
  75182. outputLiminance = _this._hdrCurrentLuminance;
  75183. }
  75184. else {
  75185. var dt = (lastTime - time) / 1000.0;
  75186. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75187. outputLiminance += _this.hdrDecreaseRate * dt;
  75188. }
  75189. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75190. outputLiminance -= _this.hdrIncreaseRate * dt;
  75191. }
  75192. else {
  75193. outputLiminance = _this._hdrCurrentLuminance;
  75194. }
  75195. }
  75196. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75197. effect.setFloat("averageLuminance", outputLiminance);
  75198. lastTime = time;
  75199. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75200. };
  75201. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75202. };
  75203. // Create lens flare post-process
  75204. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75205. var _this = this;
  75206. 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);
  75207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75208. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75209. 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);
  75210. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75211. var resolution = new BABYLON.Vector2(0, 0);
  75212. // Lens flare
  75213. this.lensFlarePostProcess.onApply = function (effect) {
  75214. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75215. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75216. effect.setFloat("strength", _this.lensFlareStrength);
  75217. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75218. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75219. // Shift
  75220. resolution.x = _this.lensFlarePostProcess.width;
  75221. resolution.y = _this.lensFlarePostProcess.height;
  75222. effect.setVector2("resolution", resolution);
  75223. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75224. };
  75225. // Compose
  75226. 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);
  75227. 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);
  75228. this.lensFlareComposePostProcess.onApply = function (effect) {
  75229. if (!_this._scene.activeCamera) {
  75230. return;
  75231. }
  75232. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75233. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75234. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75235. // Lens start rotation matrix
  75236. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75237. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75238. 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));
  75239. camRot *= 4.0;
  75240. 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);
  75241. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75242. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75243. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75244. };
  75245. };
  75246. // Create depth-of-field post-process
  75247. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75248. var _this = this;
  75249. 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);
  75250. this.depthOfFieldPostProcess.onApply = function (effect) {
  75251. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75252. effect.setTexture("depthSampler", _this._getDepthTexture());
  75253. effect.setFloat("distance", _this.depthOfFieldDistance);
  75254. };
  75255. // Add to pipeline
  75256. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75257. };
  75258. // Create motion blur post-process
  75259. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75260. var _this = this;
  75261. 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);
  75262. var motionScale = 0;
  75263. var prevViewProjection = BABYLON.Matrix.Identity();
  75264. var invViewProjection = BABYLON.Matrix.Identity();
  75265. var viewProjection = BABYLON.Matrix.Identity();
  75266. var screenSize = BABYLON.Vector2.Zero();
  75267. this.motionBlurPostProcess.onApply = function (effect) {
  75268. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75269. viewProjection.invertToRef(invViewProjection);
  75270. effect.setMatrix("inverseViewProjection", invViewProjection);
  75271. effect.setMatrix("prevViewProjection", prevViewProjection);
  75272. prevViewProjection = viewProjection;
  75273. screenSize.x = _this.motionBlurPostProcess.width;
  75274. screenSize.y = _this.motionBlurPostProcess.height;
  75275. effect.setVector2("screenSize", screenSize);
  75276. motionScale = scene.getEngine().getFps() / 60.0;
  75277. effect.setFloat("motionScale", motionScale);
  75278. effect.setFloat("motionStrength", _this.motionStrength);
  75279. effect.setTexture("depthSampler", _this._getDepthTexture());
  75280. };
  75281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75282. };
  75283. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75284. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75285. var renderer = this._scene.enableGeometryBufferRenderer();
  75286. return renderer.getGBuffer().textures[0];
  75287. }
  75288. return this._scene.enableDepthRenderer().getDepthMap();
  75289. };
  75290. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75291. for (var i = 0; i < this._cameras.length; i++) {
  75292. var camera = this._cameras[i];
  75293. if (this.originalPostProcess) {
  75294. this.originalPostProcess.dispose(camera);
  75295. }
  75296. if (this.downSampleX4PostProcess) {
  75297. this.downSampleX4PostProcess.dispose(camera);
  75298. }
  75299. if (this.brightPassPostProcess) {
  75300. this.brightPassPostProcess.dispose(camera);
  75301. }
  75302. if (this.textureAdderPostProcess) {
  75303. this.textureAdderPostProcess.dispose(camera);
  75304. }
  75305. if (this.textureAdderFinalPostProcess) {
  75306. this.textureAdderFinalPostProcess.dispose(camera);
  75307. }
  75308. if (this.volumetricLightPostProcess) {
  75309. this.volumetricLightPostProcess.dispose(camera);
  75310. }
  75311. if (this.volumetricLightSmoothXPostProcess) {
  75312. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75313. }
  75314. if (this.volumetricLightSmoothYPostProcess) {
  75315. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75316. }
  75317. if (this.volumetricLightMergePostProces) {
  75318. this.volumetricLightMergePostProces.dispose(camera);
  75319. }
  75320. if (this.volumetricLightFinalPostProcess) {
  75321. this.volumetricLightFinalPostProcess.dispose(camera);
  75322. }
  75323. if (this.lensFlarePostProcess) {
  75324. this.lensFlarePostProcess.dispose(camera);
  75325. }
  75326. if (this.lensFlareComposePostProcess) {
  75327. this.lensFlareComposePostProcess.dispose(camera);
  75328. }
  75329. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75330. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75331. }
  75332. if (this.luminancePostProcess) {
  75333. this.luminancePostProcess.dispose(camera);
  75334. }
  75335. if (this.hdrPostProcess) {
  75336. this.hdrPostProcess.dispose(camera);
  75337. }
  75338. if (this.hdrFinalPostProcess) {
  75339. this.hdrFinalPostProcess.dispose(camera);
  75340. }
  75341. if (this.depthOfFieldPostProcess) {
  75342. this.depthOfFieldPostProcess.dispose(camera);
  75343. }
  75344. if (this.motionBlurPostProcess) {
  75345. this.motionBlurPostProcess.dispose(camera);
  75346. }
  75347. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75348. this.blurHPostProcesses[j].dispose(camera);
  75349. }
  75350. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75351. this.blurVPostProcesses[j].dispose(camera);
  75352. }
  75353. }
  75354. this.originalPostProcess = null;
  75355. this.downSampleX4PostProcess = null;
  75356. this.brightPassPostProcess = null;
  75357. this.textureAdderPostProcess = null;
  75358. this.textureAdderFinalPostProcess = null;
  75359. this.volumetricLightPostProcess = null;
  75360. this.volumetricLightSmoothXPostProcess = null;
  75361. this.volumetricLightSmoothYPostProcess = null;
  75362. this.volumetricLightMergePostProces = null;
  75363. this.volumetricLightFinalPostProcess = null;
  75364. this.lensFlarePostProcess = null;
  75365. this.lensFlareComposePostProcess = null;
  75366. this.luminancePostProcess = null;
  75367. this.hdrPostProcess = null;
  75368. this.hdrFinalPostProcess = null;
  75369. this.depthOfFieldPostProcess = null;
  75370. this.motionBlurPostProcess = null;
  75371. this.luminanceDownSamplePostProcesses = [];
  75372. this.blurHPostProcesses = [];
  75373. this.blurVPostProcesses = [];
  75374. };
  75375. /**
  75376. * Dispose of the pipeline and stop all post processes
  75377. */
  75378. StandardRenderingPipeline.prototype.dispose = function () {
  75379. this._disposePostProcesses();
  75380. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75381. _super.prototype.dispose.call(this);
  75382. };
  75383. /**
  75384. * Serialize the rendering pipeline (Used when exporting)
  75385. * @returns the serialized object
  75386. */
  75387. StandardRenderingPipeline.prototype.serialize = function () {
  75388. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75389. if (this.sourceLight) {
  75390. serializationObject.sourceLightId = this.sourceLight.id;
  75391. }
  75392. serializationObject.customType = "StandardRenderingPipeline";
  75393. return serializationObject;
  75394. };
  75395. /**
  75396. * Parse the serialized pipeline
  75397. * @param source Source pipeline.
  75398. * @param scene The scene to load the pipeline to.
  75399. * @param rootUrl The URL of the serialized pipeline.
  75400. * @returns An instantiated pipeline from the serialized object.
  75401. */
  75402. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75403. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75404. if (source.sourceLightId) {
  75405. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75406. }
  75407. return p;
  75408. };
  75409. // Luminance steps
  75410. StandardRenderingPipeline.LuminanceSteps = 6;
  75411. __decorate([
  75412. BABYLON.serialize()
  75413. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75414. __decorate([
  75415. BABYLON.serialize()
  75416. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75417. __decorate([
  75418. BABYLON.serialize()
  75419. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75420. __decorate([
  75421. BABYLON.serialize()
  75422. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75423. __decorate([
  75424. BABYLON.serializeAsTexture("lensTexture")
  75425. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75426. __decorate([
  75427. BABYLON.serialize()
  75428. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75429. __decorate([
  75430. BABYLON.serialize()
  75431. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75432. __decorate([
  75433. BABYLON.serialize()
  75434. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75435. __decorate([
  75436. BABYLON.serialize()
  75437. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75438. __decorate([
  75439. BABYLON.serialize()
  75440. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75441. __decorate([
  75442. BABYLON.serialize()
  75443. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75444. __decorate([
  75445. BABYLON.serializeAsTexture("lensColorTexture")
  75446. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75447. __decorate([
  75448. BABYLON.serialize()
  75449. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75450. __decorate([
  75451. BABYLON.serialize()
  75452. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75453. __decorate([
  75454. BABYLON.serialize()
  75455. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75456. __decorate([
  75457. BABYLON.serialize()
  75458. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75459. __decorate([
  75460. BABYLON.serializeAsTexture("lensStarTexture")
  75461. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75462. __decorate([
  75463. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75464. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75465. __decorate([
  75466. BABYLON.serialize()
  75467. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75468. __decorate([
  75469. BABYLON.serialize()
  75470. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75471. __decorate([
  75472. BABYLON.serialize()
  75473. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75474. __decorate([
  75475. BABYLON.serialize()
  75476. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75477. __decorate([
  75478. BABYLON.serialize()
  75479. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75480. __decorate([
  75481. BABYLON.serialize()
  75482. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75483. __decorate([
  75484. BABYLON.serialize()
  75485. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75486. __decorate([
  75487. BABYLON.serialize()
  75488. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75489. __decorate([
  75490. BABYLON.serialize()
  75491. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75492. __decorate([
  75493. BABYLON.serialize()
  75494. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75495. __decorate([
  75496. BABYLON.serialize()
  75497. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75498. __decorate([
  75499. BABYLON.serialize()
  75500. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75501. return StandardRenderingPipeline;
  75502. }(BABYLON.PostProcessRenderPipeline));
  75503. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75504. })(BABYLON || (BABYLON = {}));
  75505. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75506. var BABYLON;
  75507. (function (BABYLON) {
  75508. var FxaaPostProcess = /** @class */ (function (_super) {
  75509. __extends(FxaaPostProcess, _super);
  75510. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75511. if (camera === void 0) { camera = null; }
  75512. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75513. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75514. var defines = _this._getDefines();
  75515. _this.updateEffect(defines);
  75516. _this.onApplyObservable.add(function (effect) {
  75517. var texelSize = _this.texelSize;
  75518. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75519. });
  75520. return _this;
  75521. }
  75522. FxaaPostProcess.prototype._getDefines = function () {
  75523. var engine = this.getEngine();
  75524. if (!engine) {
  75525. return null;
  75526. }
  75527. var glInfo = engine.getGlInfo();
  75528. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75529. return "#define MALI 1\n";
  75530. }
  75531. return null;
  75532. };
  75533. return FxaaPostProcess;
  75534. }(BABYLON.PostProcess));
  75535. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75536. })(BABYLON || (BABYLON = {}));
  75537. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75538. var BABYLON;
  75539. (function (BABYLON) {
  75540. /**
  75541. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75542. */
  75543. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75544. __extends(ChromaticAberrationPostProcess, _super);
  75545. /**
  75546. * Creates a new instance ChromaticAberrationPostProcess
  75547. * @param name The name of the effect.
  75548. * @param screenWidth The width of the screen to apply the effect on.
  75549. * @param screenHeight The height of the screen to apply the effect on.
  75550. * @param options The required width/height ratio to downsize to before computing the render pass.
  75551. * @param camera The camera to apply the render pass to.
  75552. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75553. * @param engine The engine which the post process will be applied. (default: current engine)
  75554. * @param reusable If the post process can be reused on the same frame. (default: false)
  75555. * @param textureType Type of textures used when performing the post process. (default: 0)
  75556. * @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)
  75557. */
  75558. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75559. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75560. if (blockCompilation === void 0) { blockCompilation = false; }
  75561. 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;
  75562. /**
  75563. * The amount of seperation of rgb channels (default: 30)
  75564. */
  75565. _this.aberrationAmount = 30;
  75566. /**
  75567. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75568. */
  75569. _this.radialIntensity = 0;
  75570. /**
  75571. * 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))
  75572. */
  75573. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75574. /**
  75575. * 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))
  75576. */
  75577. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75578. _this.onApplyObservable.add(function (effect) {
  75579. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75580. effect.setFloat('screen_width', screenWidth);
  75581. effect.setFloat('screen_height', screenHeight);
  75582. effect.setFloat('radialIntensity', _this.radialIntensity);
  75583. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75584. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75585. });
  75586. return _this;
  75587. }
  75588. return ChromaticAberrationPostProcess;
  75589. }(BABYLON.PostProcess));
  75590. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75591. })(BABYLON || (BABYLON = {}));
  75592. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75593. var BABYLON;
  75594. (function (BABYLON) {
  75595. /**
  75596. * The GrainPostProcess adds noise to the image at mid luminance levels
  75597. */
  75598. var GrainPostProcess = /** @class */ (function (_super) {
  75599. __extends(GrainPostProcess, _super);
  75600. /**
  75601. * Creates a new instance of @see GrainPostProcess
  75602. * @param name The name of the effect.
  75603. * @param options The required width/height ratio to downsize to before computing the render pass.
  75604. * @param camera The camera to apply the render pass to.
  75605. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75606. * @param engine The engine which the post process will be applied. (default: current engine)
  75607. * @param reusable If the post process can be reused on the same frame. (default: false)
  75608. * @param textureType Type of textures used when performing the post process. (default: 0)
  75609. * @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)
  75610. */
  75611. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75612. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75613. if (blockCompilation === void 0) { blockCompilation = false; }
  75614. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75615. /**
  75616. * The intensity of the grain added (default: 30)
  75617. */
  75618. _this.intensity = 30;
  75619. /**
  75620. * If the grain should be randomized on every frame
  75621. */
  75622. _this.animated = false;
  75623. _this.onApplyObservable.add(function (effect) {
  75624. effect.setFloat('intensity', _this.intensity);
  75625. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75626. });
  75627. return _this;
  75628. }
  75629. return GrainPostProcess;
  75630. }(BABYLON.PostProcess));
  75631. BABYLON.GrainPostProcess = GrainPostProcess;
  75632. })(BABYLON || (BABYLON = {}));
  75633. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75634. var BABYLON;
  75635. (function (BABYLON) {
  75636. /**
  75637. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75638. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75639. */
  75640. var SharpenPostProcess = /** @class */ (function (_super) {
  75641. __extends(SharpenPostProcess, _super);
  75642. /**
  75643. * Creates a new instance ConvolutionPostProcess
  75644. * @param name The name of the effect.
  75645. * @param options The required width/height ratio to downsize to before computing the render pass.
  75646. * @param camera The camera to apply the render pass to.
  75647. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75648. * @param engine The engine which the post process will be applied. (default: current engine)
  75649. * @param reusable If the post process can be reused on the same frame. (default: false)
  75650. * @param textureType Type of textures used when performing the post process. (default: 0)
  75651. * @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)
  75652. */
  75653. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75654. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75655. if (blockCompilation === void 0) { blockCompilation = false; }
  75656. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75657. /**
  75658. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75659. */
  75660. _this.colorAmount = 1.0;
  75661. /**
  75662. * How much sharpness should be applied (default: 0.3)
  75663. */
  75664. _this.edgeAmount = 0.3;
  75665. _this.onApply = function (effect) {
  75666. effect.setFloat2("screenSize", _this.width, _this.height);
  75667. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75668. };
  75669. return _this;
  75670. }
  75671. return SharpenPostProcess;
  75672. }(BABYLON.PostProcess));
  75673. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75674. })(BABYLON || (BABYLON = {}));
  75675. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75676. var BABYLON;
  75677. (function (BABYLON) {
  75678. /**
  75679. * The Blur Post Process which blurs an image based on a kernel and direction.
  75680. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75681. */
  75682. var BlurPostProcess = /** @class */ (function (_super) {
  75683. __extends(BlurPostProcess, _super);
  75684. /**
  75685. * Creates a new instance BlurPostProcess
  75686. * @param name The name of the effect.
  75687. * @param direction The direction in which to blur the image.
  75688. * @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.
  75689. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75690. * @param camera The camera to apply the render pass to.
  75691. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75692. * @param engine The engine which the post process will be applied. (default: current engine)
  75693. * @param reusable If the post process can be reused on the same frame. (default: false)
  75694. * @param textureType Type of textures used when performing the post process. (default: 0)
  75695. * @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)
  75696. */
  75697. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75698. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75699. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75700. if (defines === void 0) { defines = ""; }
  75701. if (blockCompilation === void 0) { blockCompilation = false; }
  75702. 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;
  75703. _this.direction = direction;
  75704. _this.blockCompilation = blockCompilation;
  75705. _this._packedFloat = false;
  75706. _this._staticDefines = "";
  75707. _this._staticDefines = defines;
  75708. _this.onApplyObservable.add(function (effect) {
  75709. if (_this._outputTexture) {
  75710. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75711. }
  75712. else {
  75713. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75714. }
  75715. });
  75716. _this.kernel = kernel;
  75717. return _this;
  75718. }
  75719. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75720. /**
  75721. * Gets the length in pixels of the blur sample region
  75722. */
  75723. get: function () {
  75724. return this._idealKernel;
  75725. },
  75726. /**
  75727. * Sets the length in pixels of the blur sample region
  75728. */
  75729. set: function (v) {
  75730. if (this._idealKernel === v) {
  75731. return;
  75732. }
  75733. v = Math.max(v, 1);
  75734. this._idealKernel = v;
  75735. this._kernel = this._nearestBestKernel(v);
  75736. if (!this.blockCompilation) {
  75737. this._updateParameters();
  75738. }
  75739. },
  75740. enumerable: true,
  75741. configurable: true
  75742. });
  75743. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75744. /**
  75745. * Gets wether or not the blur is unpacking/repacking floats
  75746. */
  75747. get: function () {
  75748. return this._packedFloat;
  75749. },
  75750. /**
  75751. * Sets wether or not the blur needs to unpack/repack floats
  75752. */
  75753. set: function (v) {
  75754. if (this._packedFloat === v) {
  75755. return;
  75756. }
  75757. this._packedFloat = v;
  75758. if (!this.blockCompilation) {
  75759. this._updateParameters();
  75760. }
  75761. },
  75762. enumerable: true,
  75763. configurable: true
  75764. });
  75765. /**
  75766. * Updates the effect with the current post process compile time values and recompiles the shader.
  75767. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75768. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75769. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75770. * @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
  75771. * @param onCompiled Called when the shader has been compiled.
  75772. * @param onError Called if there is an error when compiling a shader.
  75773. */
  75774. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75775. if (defines === void 0) { defines = null; }
  75776. if (uniforms === void 0) { uniforms = null; }
  75777. if (samplers === void 0) { samplers = null; }
  75778. this._updateParameters(onCompiled, onError);
  75779. };
  75780. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75781. // Generate sampling offsets and weights
  75782. var N = this._kernel;
  75783. var centerIndex = (N - 1) / 2;
  75784. // Generate Gaussian sampling weights over kernel
  75785. var offsets = [];
  75786. var weights = [];
  75787. var totalWeight = 0;
  75788. for (var i = 0; i < N; i++) {
  75789. var u = i / (N - 1);
  75790. var w = this._gaussianWeight(u * 2.0 - 1);
  75791. offsets[i] = (i - centerIndex);
  75792. weights[i] = w;
  75793. totalWeight += w;
  75794. }
  75795. // Normalize weights
  75796. for (var i = 0; i < weights.length; i++) {
  75797. weights[i] /= totalWeight;
  75798. }
  75799. // Optimize: combine samples to take advantage of hardware linear sampling
  75800. // Walk from left to center, combining pairs (symmetrically)
  75801. var linearSamplingWeights = [];
  75802. var linearSamplingOffsets = [];
  75803. var linearSamplingMap = [];
  75804. for (var i = 0; i <= centerIndex; i += 2) {
  75805. var j = Math.min(i + 1, Math.floor(centerIndex));
  75806. var singleCenterSample = i === j;
  75807. if (singleCenterSample) {
  75808. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75809. }
  75810. else {
  75811. var sharedCell = j === centerIndex;
  75812. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75813. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75814. if (offsetLinear === 0) {
  75815. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75816. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75817. }
  75818. else {
  75819. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75820. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75821. }
  75822. }
  75823. }
  75824. for (var i = 0; i < linearSamplingMap.length; i++) {
  75825. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75826. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75827. }
  75828. // Replace with optimized
  75829. offsets = linearSamplingOffsets;
  75830. weights = linearSamplingWeights;
  75831. // Generate shaders
  75832. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75833. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75834. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75835. var defines = "";
  75836. defines += this._staticDefines;
  75837. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75838. if (this._staticDefines.indexOf("DOF") != -1) {
  75839. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75840. varyingCount--;
  75841. }
  75842. for (var i = 0; i < varyingCount; i++) {
  75843. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75844. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75845. }
  75846. var depCount = 0;
  75847. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75848. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75849. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75850. depCount++;
  75851. }
  75852. if (this.packedFloat) {
  75853. defines += "#define PACKEDFLOAT 1";
  75854. }
  75855. this.blockCompilation = false;
  75856. _super.prototype.updateEffect.call(this, defines, null, null, {
  75857. varyingCount: varyingCount,
  75858. depCount: depCount
  75859. }, onCompiled, onError);
  75860. };
  75861. /**
  75862. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75863. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75864. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75865. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75866. * The gaps between physical kernels are compensated for in the weighting of the samples
  75867. * @param idealKernel Ideal blur kernel.
  75868. * @return Nearest best kernel.
  75869. */
  75870. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75871. var v = Math.round(idealKernel);
  75872. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75873. var k = _a[_i];
  75874. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75875. return Math.max(k, 3);
  75876. }
  75877. }
  75878. return Math.max(v, 3);
  75879. };
  75880. /**
  75881. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75882. * @param x The point on the Gaussian distribution to sample.
  75883. * @return the value of the Gaussian function at x.
  75884. */
  75885. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75886. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75887. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75888. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75889. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75890. // truncated at around 1.3% of peak strength.
  75891. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75892. var sigma = (1 / 3);
  75893. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75894. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75895. var weight = (1.0 / denominator) * Math.exp(exponent);
  75896. return weight;
  75897. };
  75898. /**
  75899. * Generates a string that can be used as a floating point number in GLSL.
  75900. * @param x Value to print.
  75901. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75902. * @return GLSL float string.
  75903. */
  75904. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75905. if (decimalFigures === void 0) { decimalFigures = 8; }
  75906. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75907. };
  75908. return BlurPostProcess;
  75909. }(BABYLON.PostProcess));
  75910. BABYLON.BlurPostProcess = BlurPostProcess;
  75911. })(BABYLON || (BABYLON = {}));
  75912. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75913. var BABYLON;
  75914. (function (BABYLON) {
  75915. /**
  75916. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75917. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75918. * based on samples that have a large difference in distance than the center pixel.
  75919. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75920. */
  75921. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75922. __extends(DepthOfFieldBlurPostProcess, _super);
  75923. /**
  75924. * Creates a new instance CircleOfConfusionPostProcess
  75925. * @param name The name of the effect.
  75926. * @param scene The scene the effect belongs to.
  75927. * @param direction The direction the blur should be applied.
  75928. * @param kernel The size of the kernel used to blur.
  75929. * @param options The required width/height ratio to downsize to before computing the render pass.
  75930. * @param camera The camera to apply the render pass to.
  75931. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75932. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75933. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75934. * @param engine The engine which the post process will be applied. (default: current engine)
  75935. * @param reusable If the post process can be reused on the same frame. (default: false)
  75936. * @param textureType Type of textures used when performing the post process. (default: 0)
  75937. * @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)
  75938. */
  75939. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75940. if (imageToBlur === void 0) { imageToBlur = null; }
  75941. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75942. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75943. if (blockCompilation === void 0) { blockCompilation = false; }
  75944. 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;
  75945. _this.direction = direction;
  75946. _this.onApplyObservable.add(function (effect) {
  75947. if (imageToBlur != null) {
  75948. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75949. }
  75950. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75951. if (scene.activeCamera) {
  75952. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75953. }
  75954. });
  75955. return _this;
  75956. }
  75957. return DepthOfFieldBlurPostProcess;
  75958. }(BABYLON.BlurPostProcess));
  75959. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75960. })(BABYLON || (BABYLON = {}));
  75961. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75962. var BABYLON;
  75963. (function (BABYLON) {
  75964. /**
  75965. * Options to be set when merging outputs from the default pipeline.
  75966. */
  75967. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75968. function DepthOfFieldMergePostProcessOptions() {
  75969. }
  75970. return DepthOfFieldMergePostProcessOptions;
  75971. }());
  75972. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75973. /**
  75974. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75975. */
  75976. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75977. __extends(DepthOfFieldMergePostProcess, _super);
  75978. /**
  75979. * Creates a new instance of DepthOfFieldMergePostProcess
  75980. * @param name The name of the effect.
  75981. * @param originalFromInput Post process which's input will be used for the merge.
  75982. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75983. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75984. * @param options The required width/height ratio to downsize to before computing the render pass.
  75985. * @param camera The camera to apply the render pass to.
  75986. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75987. * @param engine The engine which the post process will be applied. (default: current engine)
  75988. * @param reusable If the post process can be reused on the same frame. (default: false)
  75989. * @param textureType Type of textures used when performing the post process. (default: 0)
  75990. * @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)
  75991. */
  75992. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75993. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75994. if (blockCompilation === void 0) { blockCompilation = false; }
  75995. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75996. _this.blurSteps = blurSteps;
  75997. _this.onApplyObservable.add(function (effect) {
  75998. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75999. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76000. blurSteps.forEach(function (step, index) {
  76001. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  76002. });
  76003. });
  76004. if (!blockCompilation) {
  76005. _this.updateEffect();
  76006. }
  76007. return _this;
  76008. }
  76009. /**
  76010. * Updates the effect with the current post process compile time values and recompiles the shader.
  76011. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76012. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76013. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76014. * @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
  76015. * @param onCompiled Called when the shader has been compiled.
  76016. * @param onError Called if there is an error when compiling a shader.
  76017. */
  76018. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76019. if (defines === void 0) { defines = null; }
  76020. if (uniforms === void 0) { uniforms = null; }
  76021. if (samplers === void 0) { samplers = null; }
  76022. if (!defines) {
  76023. defines = "";
  76024. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  76025. }
  76026. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  76027. };
  76028. return DepthOfFieldMergePostProcess;
  76029. }(BABYLON.PostProcess));
  76030. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  76031. })(BABYLON || (BABYLON = {}));
  76032. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  76033. var BABYLON;
  76034. (function (BABYLON) {
  76035. /**
  76036. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  76037. */
  76038. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  76039. __extends(CircleOfConfusionPostProcess, _super);
  76040. /**
  76041. * Creates a new instance CircleOfConfusionPostProcess
  76042. * @param name The name of the effect.
  76043. * @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.
  76044. * @param options The required width/height ratio to downsize to before computing the render pass.
  76045. * @param camera The camera to apply the render pass to.
  76046. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76047. * @param engine The engine which the post process will be applied. (default: current engine)
  76048. * @param reusable If the post process can be reused on the same frame. (default: false)
  76049. * @param textureType Type of textures used when performing the post process. (default: 0)
  76050. * @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)
  76051. */
  76052. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76053. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76054. if (blockCompilation === void 0) { blockCompilation = false; }
  76055. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76056. /**
  76057. * 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.
  76058. */
  76059. _this.lensSize = 50;
  76060. /**
  76061. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76062. */
  76063. _this.fStop = 1.4;
  76064. /**
  76065. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76066. */
  76067. _this.focusDistance = 2000;
  76068. /**
  76069. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  76070. */
  76071. _this.focalLength = 50;
  76072. _this._depthTexture = null;
  76073. _this._depthTexture = depthTexture;
  76074. _this.onApplyObservable.add(function (effect) {
  76075. if (!_this._depthTexture) {
  76076. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  76077. return;
  76078. }
  76079. effect.setTexture("depthSampler", _this._depthTexture);
  76080. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  76081. var aperture = _this.lensSize / _this.fStop;
  76082. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  76083. effect.setFloat('focusDistance', _this.focusDistance);
  76084. effect.setFloat('cocPrecalculation', cocPrecalculation);
  76085. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  76086. });
  76087. return _this;
  76088. }
  76089. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  76090. /**
  76091. * 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.
  76092. */
  76093. set: function (value) {
  76094. this._depthTexture = value;
  76095. },
  76096. enumerable: true,
  76097. configurable: true
  76098. });
  76099. return CircleOfConfusionPostProcess;
  76100. }(BABYLON.PostProcess));
  76101. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  76102. })(BABYLON || (BABYLON = {}));
  76103. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  76104. var BABYLON;
  76105. (function (BABYLON) {
  76106. /**
  76107. * Specifies the level of max blur that should be applied when using the depth of field effect
  76108. */
  76109. var DepthOfFieldEffectBlurLevel;
  76110. (function (DepthOfFieldEffectBlurLevel) {
  76111. /**
  76112. * Subtle blur
  76113. */
  76114. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  76115. /**
  76116. * Medium blur
  76117. */
  76118. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  76119. /**
  76120. * Large blur
  76121. */
  76122. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  76123. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  76124. ;
  76125. /**
  76126. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  76127. */
  76128. var DepthOfFieldEffect = /** @class */ (function (_super) {
  76129. __extends(DepthOfFieldEffect, _super);
  76130. /**
  76131. * Creates a new instance DepthOfFieldEffect
  76132. * @param scene The scene the effect belongs to.
  76133. * @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.
  76134. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76135. * @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)
  76136. */
  76137. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  76138. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  76139. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76140. if (blockCompilation === void 0) { blockCompilation = false; }
  76141. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  76142. return _this._effects;
  76143. }, true) || this;
  76144. /**
  76145. * Internal post processes in depth of field effect
  76146. */
  76147. _this._effects = [];
  76148. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  76149. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76150. // 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)
  76151. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  76152. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76153. _this._depthOfFieldBlurY = [];
  76154. _this._depthOfFieldBlurX = [];
  76155. var blurCount = 1;
  76156. var kernelSize = 15;
  76157. switch (blurLevel) {
  76158. case DepthOfFieldEffectBlurLevel.High: {
  76159. blurCount = 3;
  76160. kernelSize = 51;
  76161. break;
  76162. }
  76163. case DepthOfFieldEffectBlurLevel.Medium: {
  76164. blurCount = 2;
  76165. kernelSize = 31;
  76166. break;
  76167. }
  76168. default: {
  76169. kernelSize = 15;
  76170. blurCount = 1;
  76171. break;
  76172. }
  76173. }
  76174. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76175. var ratio = 1.0;
  76176. for (var i = 0; i < blurCount; i++) {
  76177. 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);
  76178. blurY.autoClear = false;
  76179. ratio = 0.75 / Math.pow(2, i);
  76180. 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);
  76181. blurX.autoClear = false;
  76182. _this._depthOfFieldBlurY.push(blurY);
  76183. _this._depthOfFieldBlurX.push(blurX);
  76184. }
  76185. // Set all post processes on the effect.
  76186. _this._effects = [_this._circleOfConfusion];
  76187. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76188. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76189. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76190. }
  76191. // Merge blurred images with original image based on circleOfConfusion
  76192. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76193. _this._dofMerge.autoClear = false;
  76194. _this._effects.push(_this._dofMerge);
  76195. return _this;
  76196. }
  76197. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76198. get: function () {
  76199. return this._circleOfConfusion.focalLength;
  76200. },
  76201. /**
  76202. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76203. */
  76204. set: function (value) {
  76205. this._circleOfConfusion.focalLength = value;
  76206. },
  76207. enumerable: true,
  76208. configurable: true
  76209. });
  76210. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76211. get: function () {
  76212. return this._circleOfConfusion.fStop;
  76213. },
  76214. /**
  76215. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76216. */
  76217. set: function (value) {
  76218. this._circleOfConfusion.fStop = value;
  76219. },
  76220. enumerable: true,
  76221. configurable: true
  76222. });
  76223. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76224. get: function () {
  76225. return this._circleOfConfusion.focusDistance;
  76226. },
  76227. /**
  76228. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76229. */
  76230. set: function (value) {
  76231. this._circleOfConfusion.focusDistance = value;
  76232. },
  76233. enumerable: true,
  76234. configurable: true
  76235. });
  76236. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76237. get: function () {
  76238. return this._circleOfConfusion.lensSize;
  76239. },
  76240. /**
  76241. * 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.
  76242. */
  76243. set: function (value) {
  76244. this._circleOfConfusion.lensSize = value;
  76245. },
  76246. enumerable: true,
  76247. configurable: true
  76248. });
  76249. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76250. /**
  76251. * 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.
  76252. */
  76253. set: function (value) {
  76254. this._circleOfConfusion.depthTexture = value;
  76255. },
  76256. enumerable: true,
  76257. configurable: true
  76258. });
  76259. /**
  76260. * Disposes each of the internal effects for a given camera.
  76261. * @param camera The camera to dispose the effect on.
  76262. */
  76263. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76264. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76265. this._effects[effectIndex].dispose(camera);
  76266. }
  76267. };
  76268. /**
  76269. * Internal
  76270. */
  76271. DepthOfFieldEffect.prototype._updateEffects = function () {
  76272. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76273. this._effects[effectIndex].updateEffect();
  76274. }
  76275. };
  76276. /**
  76277. * Internal
  76278. * @returns if all the contained post processes are ready.
  76279. */
  76280. DepthOfFieldEffect.prototype._isReady = function () {
  76281. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76282. if (!this._effects[effectIndex].isReady()) {
  76283. return false;
  76284. }
  76285. }
  76286. return true;
  76287. };
  76288. return DepthOfFieldEffect;
  76289. }(BABYLON.PostProcessRenderEffect));
  76290. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76291. })(BABYLON || (BABYLON = {}));
  76292. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76293. var BABYLON;
  76294. (function (BABYLON) {
  76295. /**
  76296. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76297. */
  76298. var BloomMergePostProcess = /** @class */ (function (_super) {
  76299. __extends(BloomMergePostProcess, _super);
  76300. /**
  76301. * Creates a new instance of @see BloomMergePostProcess
  76302. * @param name The name of the effect.
  76303. * @param originalFromInput Post process which's input will be used for the merge.
  76304. * @param blurred Blurred highlights post process which's output will be used.
  76305. * @param weight Weight of the bloom to be added to the original input.
  76306. * @param options The required width/height ratio to downsize to before computing the render pass.
  76307. * @param camera The camera to apply the render pass to.
  76308. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76309. * @param engine The engine which the post process will be applied. (default: current engine)
  76310. * @param reusable If the post process can be reused on the same frame. (default: false)
  76311. * @param textureType Type of textures used when performing the post process. (default: 0)
  76312. * @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)
  76313. */
  76314. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76315. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76316. if (blockCompilation === void 0) { blockCompilation = false; }
  76317. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76318. _this.weight = weight;
  76319. _this.onApplyObservable.add(function (effect) {
  76320. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76321. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76322. effect.setFloat("bloomWeight", _this.weight);
  76323. });
  76324. if (!blockCompilation) {
  76325. _this.updateEffect();
  76326. }
  76327. return _this;
  76328. }
  76329. return BloomMergePostProcess;
  76330. }(BABYLON.PostProcess));
  76331. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76332. })(BABYLON || (BABYLON = {}));
  76333. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76334. var BABYLON;
  76335. (function (BABYLON) {
  76336. /**
  76337. * 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.
  76338. */
  76339. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76340. __extends(ExtractHighlightsPostProcess, _super);
  76341. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76342. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76343. if (blockCompilation === void 0) { blockCompilation = false; }
  76344. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76345. /**
  76346. * The luminance threshold, pixels below this value will be set to black.
  76347. */
  76348. _this.threshold = 0.9;
  76349. /**
  76350. * Internal
  76351. */
  76352. _this._exposure = 1;
  76353. /**
  76354. * Post process which has the input texture to be used when performing highlight extraction
  76355. */
  76356. _this._inputPostProcess = null;
  76357. _this.onApplyObservable.add(function (effect) {
  76358. if (_this._inputPostProcess) {
  76359. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76360. }
  76361. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76362. effect.setFloat('exposure', _this._exposure);
  76363. });
  76364. return _this;
  76365. }
  76366. return ExtractHighlightsPostProcess;
  76367. }(BABYLON.PostProcess));
  76368. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76369. })(BABYLON || (BABYLON = {}));
  76370. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76371. var BABYLON;
  76372. (function (BABYLON) {
  76373. /**
  76374. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76375. */
  76376. var BloomEffect = /** @class */ (function (_super) {
  76377. __extends(BloomEffect, _super);
  76378. /**
  76379. * Creates a new instance of @see BloomEffect
  76380. * @param scene The scene the effect belongs to.
  76381. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76382. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76383. * @param bloomWeight The the strength of bloom.
  76384. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76385. * @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)
  76386. */
  76387. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76388. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76389. if (blockCompilation === void 0) { blockCompilation = false; }
  76390. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76391. return _this._effects;
  76392. }, true) || this;
  76393. _this.bloomScale = bloomScale;
  76394. /**
  76395. * Internal
  76396. */
  76397. _this._effects = [];
  76398. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76399. _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);
  76400. _this._blurX.alwaysForcePOT = true;
  76401. _this._blurX.autoClear = false;
  76402. _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);
  76403. _this._blurY.alwaysForcePOT = true;
  76404. _this._blurY.autoClear = false;
  76405. _this.kernel = bloomKernel;
  76406. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76407. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76408. _this._merge.autoClear = false;
  76409. _this._effects.push(_this._merge);
  76410. return _this;
  76411. }
  76412. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76413. /**
  76414. * The luminance threshold to find bright areas of the image to bloom.
  76415. */
  76416. get: function () {
  76417. return this._downscale.threshold;
  76418. },
  76419. set: function (value) {
  76420. this._downscale.threshold = value;
  76421. },
  76422. enumerable: true,
  76423. configurable: true
  76424. });
  76425. Object.defineProperty(BloomEffect.prototype, "weight", {
  76426. /**
  76427. * The strength of the bloom.
  76428. */
  76429. get: function () {
  76430. return this._merge.weight;
  76431. },
  76432. set: function (value) {
  76433. this._merge.weight = value;
  76434. },
  76435. enumerable: true,
  76436. configurable: true
  76437. });
  76438. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76439. /**
  76440. * Specifies the size of the bloom blur kernel, relative to the final output size
  76441. */
  76442. get: function () {
  76443. return this._blurX.kernel / this.bloomScale;
  76444. },
  76445. set: function (value) {
  76446. this._blurX.kernel = value * this.bloomScale;
  76447. this._blurY.kernel = value * this.bloomScale;
  76448. },
  76449. enumerable: true,
  76450. configurable: true
  76451. });
  76452. /**
  76453. * Disposes each of the internal effects for a given camera.
  76454. * @param camera The camera to dispose the effect on.
  76455. */
  76456. BloomEffect.prototype.disposeEffects = function (camera) {
  76457. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76458. this._effects[effectIndex].dispose(camera);
  76459. }
  76460. };
  76461. /**
  76462. * Internal
  76463. */
  76464. BloomEffect.prototype._updateEffects = function () {
  76465. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76466. this._effects[effectIndex].updateEffect();
  76467. }
  76468. };
  76469. /**
  76470. * Internal
  76471. * @returns if all the contained post processes are ready.
  76472. */
  76473. BloomEffect.prototype._isReady = function () {
  76474. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76475. if (!this._effects[effectIndex].isReady()) {
  76476. return false;
  76477. }
  76478. }
  76479. return true;
  76480. };
  76481. return BloomEffect;
  76482. }(BABYLON.PostProcessRenderEffect));
  76483. BABYLON.BloomEffect = BloomEffect;
  76484. })(BABYLON || (BABYLON = {}));
  76485. //# sourceMappingURL=babylon.bloomEffect.js.map
  76486. var BABYLON;
  76487. (function (BABYLON) {
  76488. /**
  76489. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76490. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76491. */
  76492. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76493. __extends(DefaultRenderingPipeline, _super);
  76494. /**
  76495. * @constructor
  76496. * @param {string} name - The rendering pipeline name (default: "")
  76497. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76498. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76499. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76500. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76501. */
  76502. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76503. if (name === void 0) { name = ""; }
  76504. if (hdr === void 0) { hdr = true; }
  76505. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76506. if (automaticBuild === void 0) { automaticBuild = true; }
  76507. var _this = _super.call(this, scene.getEngine(), name) || this;
  76508. _this._camerasToBeAttached = [];
  76509. /**
  76510. * ID of the sharpen post process,
  76511. */
  76512. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76513. /**
  76514. * ID of the image processing post process;
  76515. */
  76516. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76517. /**
  76518. * ID of the Fast Approximate Anti-Aliasing post process;
  76519. */
  76520. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76521. /**
  76522. * ID of the chromatic aberration post process,
  76523. */
  76524. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76525. /**
  76526. * ID of the grain post process
  76527. */
  76528. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76529. /**
  76530. * Glow post process which adds a glow to emmisive areas of the image
  76531. */
  76532. _this._glowLayer = null;
  76533. /**
  76534. * Animations which can be used to tweak settings over a period of time
  76535. */
  76536. _this.animations = [];
  76537. _this._imageProcessingConfigurationObserver = null;
  76538. // Values
  76539. _this._sharpenEnabled = false;
  76540. _this._bloomEnabled = false;
  76541. _this._depthOfFieldEnabled = false;
  76542. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76543. _this._fxaaEnabled = false;
  76544. _this._imageProcessingEnabled = true;
  76545. _this._bloomScale = 0.5;
  76546. _this._chromaticAberrationEnabled = false;
  76547. _this._grainEnabled = false;
  76548. _this._buildAllowed = true;
  76549. _this._resizeObserver = null;
  76550. _this._hardwareScaleLevel = 1.0;
  76551. _this._bloomKernel = 64;
  76552. /**
  76553. * Specifies the weight of the bloom in the final rendering
  76554. */
  76555. _this._bloomWeight = 0.15;
  76556. /**
  76557. * Specifies the luma threshold for the area that will be blurred by the bloom
  76558. */
  76559. _this._bloomThreshold = 0.9;
  76560. _this._samples = 1;
  76561. _this._hasCleared = false;
  76562. _this._prevPostProcess = null;
  76563. _this._prevPrevPostProcess = null;
  76564. _this._cameras = cameras || scene.cameras;
  76565. _this._camerasToBeAttached = _this._cameras.slice();
  76566. _this._buildAllowed = automaticBuild;
  76567. // Initialize
  76568. _this._scene = scene;
  76569. var caps = _this._scene.getEngine().getCaps();
  76570. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76571. // Misc
  76572. if (_this._hdr) {
  76573. if (caps.textureHalfFloatRender) {
  76574. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76575. }
  76576. else if (caps.textureFloatRender) {
  76577. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76578. }
  76579. }
  76580. else {
  76581. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76582. }
  76583. // Attach
  76584. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76585. var engine = _this._scene.getEngine();
  76586. // Create post processes before hand so they can be modified before enabled.
  76587. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76588. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76589. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76590. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76591. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76592. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76593. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76594. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76595. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76596. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76597. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76598. _this.bloomKernel = _this.bloomKernel;
  76599. });
  76600. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76601. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76602. });
  76603. _this._buildPipeline();
  76604. return _this;
  76605. }
  76606. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76607. get: function () {
  76608. return this._sharpenEnabled;
  76609. },
  76610. /**
  76611. * Enable or disable the sharpen process from the pipeline
  76612. */
  76613. set: function (enabled) {
  76614. if (this._sharpenEnabled === enabled) {
  76615. return;
  76616. }
  76617. this._sharpenEnabled = enabled;
  76618. this._buildPipeline();
  76619. },
  76620. enumerable: true,
  76621. configurable: true
  76622. });
  76623. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76624. /**
  76625. * Specifies the size of the bloom blur kernel, relative to the final output size
  76626. */
  76627. get: function () {
  76628. return this._bloomKernel;
  76629. },
  76630. set: function (value) {
  76631. this._bloomKernel = value;
  76632. this.bloom.kernel = value / this._hardwareScaleLevel;
  76633. },
  76634. enumerable: true,
  76635. configurable: true
  76636. });
  76637. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76638. get: function () {
  76639. return this._bloomWeight;
  76640. },
  76641. /**
  76642. * The strength of the bloom.
  76643. */
  76644. set: function (value) {
  76645. if (this._bloomWeight === value) {
  76646. return;
  76647. }
  76648. this.bloom.weight = value;
  76649. this._bloomWeight = value;
  76650. },
  76651. enumerable: true,
  76652. configurable: true
  76653. });
  76654. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76655. get: function () {
  76656. return this._bloomThreshold;
  76657. },
  76658. /**
  76659. * The strength of the bloom.
  76660. */
  76661. set: function (value) {
  76662. if (this._bloomThreshold === value) {
  76663. return;
  76664. }
  76665. this.bloom.threshold = value;
  76666. this._bloomThreshold = value;
  76667. },
  76668. enumerable: true,
  76669. configurable: true
  76670. });
  76671. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76672. get: function () {
  76673. return this._bloomScale;
  76674. },
  76675. /**
  76676. * The scale of the bloom, lower value will provide better performance.
  76677. */
  76678. set: function (value) {
  76679. if (this._bloomScale === value) {
  76680. return;
  76681. }
  76682. this._bloomScale = value;
  76683. // recreate bloom and dispose old as this setting is not dynamic
  76684. this._rebuildBloom();
  76685. this._buildPipeline();
  76686. },
  76687. enumerable: true,
  76688. configurable: true
  76689. });
  76690. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76691. get: function () {
  76692. return this._bloomEnabled;
  76693. },
  76694. /**
  76695. * Enable or disable the bloom from the pipeline
  76696. */
  76697. set: function (enabled) {
  76698. if (this._bloomEnabled === enabled) {
  76699. return;
  76700. }
  76701. this._bloomEnabled = enabled;
  76702. this._buildPipeline();
  76703. },
  76704. enumerable: true,
  76705. configurable: true
  76706. });
  76707. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76708. // recreate bloom and dispose old as this setting is not dynamic
  76709. var oldBloom = this.bloom;
  76710. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76711. this.bloom.threshold = oldBloom.threshold;
  76712. for (var i = 0; i < this._cameras.length; i++) {
  76713. oldBloom.disposeEffects(this._cameras[i]);
  76714. }
  76715. };
  76716. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76717. /**
  76718. * If the depth of field is enabled.
  76719. */
  76720. get: function () {
  76721. return this._depthOfFieldEnabled;
  76722. },
  76723. set: function (enabled) {
  76724. if (this._depthOfFieldEnabled === enabled) {
  76725. return;
  76726. }
  76727. this._depthOfFieldEnabled = enabled;
  76728. this._buildPipeline();
  76729. },
  76730. enumerable: true,
  76731. configurable: true
  76732. });
  76733. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76734. /**
  76735. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76736. */
  76737. get: function () {
  76738. return this._depthOfFieldBlurLevel;
  76739. },
  76740. set: function (value) {
  76741. if (this._depthOfFieldBlurLevel === value) {
  76742. return;
  76743. }
  76744. this._depthOfFieldBlurLevel = value;
  76745. // recreate dof and dispose old as this setting is not dynamic
  76746. var oldDof = this.depthOfField;
  76747. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76748. this.depthOfField.focalLength = oldDof.focalLength;
  76749. this.depthOfField.focusDistance = oldDof.focusDistance;
  76750. this.depthOfField.fStop = oldDof.fStop;
  76751. this.depthOfField.lensSize = oldDof.lensSize;
  76752. for (var i = 0; i < this._cameras.length; i++) {
  76753. oldDof.disposeEffects(this._cameras[i]);
  76754. }
  76755. this._buildPipeline();
  76756. },
  76757. enumerable: true,
  76758. configurable: true
  76759. });
  76760. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76761. get: function () {
  76762. return this._fxaaEnabled;
  76763. },
  76764. /**
  76765. * If the anti aliasing is enabled.
  76766. */
  76767. set: function (enabled) {
  76768. if (this._fxaaEnabled === enabled) {
  76769. return;
  76770. }
  76771. this._fxaaEnabled = enabled;
  76772. this._buildPipeline();
  76773. },
  76774. enumerable: true,
  76775. configurable: true
  76776. });
  76777. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76778. get: function () {
  76779. return this._samples;
  76780. },
  76781. /**
  76782. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76783. */
  76784. set: function (sampleCount) {
  76785. if (this._samples === sampleCount) {
  76786. return;
  76787. }
  76788. this._samples = sampleCount;
  76789. this._buildPipeline();
  76790. },
  76791. enumerable: true,
  76792. configurable: true
  76793. });
  76794. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76795. get: function () {
  76796. return this._imageProcessingEnabled;
  76797. },
  76798. /**
  76799. * If image processing is enabled.
  76800. */
  76801. set: function (enabled) {
  76802. if (this._imageProcessingEnabled === enabled) {
  76803. return;
  76804. }
  76805. this._imageProcessingEnabled = enabled;
  76806. this._buildPipeline();
  76807. },
  76808. enumerable: true,
  76809. configurable: true
  76810. });
  76811. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76812. get: function () {
  76813. return this._glowLayer == null;
  76814. },
  76815. /**
  76816. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76817. */
  76818. set: function (enabled) {
  76819. if (enabled && !this._glowLayer) {
  76820. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76821. }
  76822. else if (!enabled && this._glowLayer) {
  76823. this._glowLayer.dispose();
  76824. this._glowLayer = null;
  76825. }
  76826. },
  76827. enumerable: true,
  76828. configurable: true
  76829. });
  76830. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76831. get: function () {
  76832. return this._chromaticAberrationEnabled;
  76833. },
  76834. /**
  76835. * Enable or disable the chromaticAberration process from the pipeline
  76836. */
  76837. set: function (enabled) {
  76838. if (this._chromaticAberrationEnabled === enabled) {
  76839. return;
  76840. }
  76841. this._chromaticAberrationEnabled = enabled;
  76842. this._buildPipeline();
  76843. },
  76844. enumerable: true,
  76845. configurable: true
  76846. });
  76847. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76848. get: function () {
  76849. return this._grainEnabled;
  76850. },
  76851. /**
  76852. * Enable or disable the grain process from the pipeline
  76853. */
  76854. set: function (enabled) {
  76855. if (this._grainEnabled === enabled) {
  76856. return;
  76857. }
  76858. this._grainEnabled = enabled;
  76859. this._buildPipeline();
  76860. },
  76861. enumerable: true,
  76862. configurable: true
  76863. });
  76864. /**
  76865. * Force the compilation of the entire pipeline.
  76866. */
  76867. DefaultRenderingPipeline.prototype.prepare = function () {
  76868. var previousState = this._buildAllowed;
  76869. this._buildAllowed = true;
  76870. this._buildPipeline();
  76871. this._buildAllowed = previousState;
  76872. };
  76873. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76874. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76875. if (this._hasCleared) {
  76876. postProcess.autoClear = false;
  76877. }
  76878. else {
  76879. postProcess.autoClear = true;
  76880. this._scene.autoClear = false;
  76881. this._hasCleared = true;
  76882. }
  76883. if (!skipTextureSharing) {
  76884. if (this._prevPrevPostProcess) {
  76885. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76886. }
  76887. else {
  76888. postProcess.useOwnOutput();
  76889. }
  76890. if (this._prevPostProcess) {
  76891. this._prevPrevPostProcess = this._prevPostProcess;
  76892. }
  76893. this._prevPostProcess = postProcess;
  76894. }
  76895. };
  76896. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76897. var _this = this;
  76898. if (!this._buildAllowed) {
  76899. return;
  76900. }
  76901. this._scene.autoClear = true;
  76902. var engine = this._scene.getEngine();
  76903. this._disposePostProcesses();
  76904. if (this._cameras !== null) {
  76905. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76906. // get back cameras to be used to reattach pipeline
  76907. this._cameras = this._camerasToBeAttached.slice();
  76908. }
  76909. this._reset();
  76910. this._prevPostProcess = null;
  76911. this._prevPrevPostProcess = null;
  76912. this._hasCleared = false;
  76913. if (this.depthOfFieldEnabled) {
  76914. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76915. this.depthOfField.depthTexture = depthTexture;
  76916. if (!this.depthOfField._isReady()) {
  76917. this.depthOfField._updateEffects();
  76918. }
  76919. this.addEffect(this.depthOfField);
  76920. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76921. }
  76922. if (this.bloomEnabled) {
  76923. if (!this.bloom._isReady()) {
  76924. this.bloom._updateEffects();
  76925. }
  76926. this.addEffect(this.bloom);
  76927. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76928. }
  76929. if (this._imageProcessingEnabled) {
  76930. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76931. if (this._hdr) {
  76932. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76933. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76934. }
  76935. else {
  76936. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76937. }
  76938. }
  76939. if (this.sharpenEnabled) {
  76940. if (!this.sharpen.isReady()) {
  76941. this.sharpen.updateEffect();
  76942. }
  76943. this.addEffect(this._sharpenEffect);
  76944. this._setAutoClearAndTextureSharing(this.sharpen);
  76945. }
  76946. if (this.grainEnabled) {
  76947. if (!this.grain.isReady()) {
  76948. this.grain.updateEffect();
  76949. }
  76950. this.addEffect(this._grainEffect);
  76951. this._setAutoClearAndTextureSharing(this.grain);
  76952. }
  76953. if (this.chromaticAberrationEnabled) {
  76954. if (!this.chromaticAberration.isReady()) {
  76955. this.chromaticAberration.updateEffect();
  76956. }
  76957. this.addEffect(this._chromaticAberrationEffect);
  76958. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76959. }
  76960. if (this.fxaaEnabled) {
  76961. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76962. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76963. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76964. }
  76965. if (this._cameras !== null) {
  76966. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76967. }
  76968. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76969. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76970. }
  76971. };
  76972. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76973. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76974. for (var i = 0; i < this._cameras.length; i++) {
  76975. var camera = this._cameras[i];
  76976. if (this.imageProcessing) {
  76977. this.imageProcessing.dispose(camera);
  76978. }
  76979. if (this.fxaa) {
  76980. this.fxaa.dispose(camera);
  76981. }
  76982. // These are created in the constructor and should not be disposed on every pipeline change
  76983. if (disposeNonRecreated) {
  76984. if (this.sharpen) {
  76985. this.sharpen.dispose(camera);
  76986. }
  76987. if (this.depthOfField) {
  76988. this.depthOfField.disposeEffects(camera);
  76989. }
  76990. if (this.bloom) {
  76991. this.bloom.disposeEffects(camera);
  76992. }
  76993. if (this.chromaticAberration) {
  76994. this.chromaticAberration.dispose(camera);
  76995. }
  76996. if (this.grain) {
  76997. this.grain.dispose(camera);
  76998. }
  76999. if (this._glowLayer) {
  77000. this._glowLayer.dispose();
  77001. }
  77002. }
  77003. }
  77004. this.imageProcessing = null;
  77005. this.fxaa = null;
  77006. if (disposeNonRecreated) {
  77007. this.sharpen = null;
  77008. this._sharpenEffect = null;
  77009. this.depthOfField = null;
  77010. this.bloom = null;
  77011. this.chromaticAberration = null;
  77012. this._chromaticAberrationEffect = null;
  77013. this.grain = null;
  77014. this._grainEffect = null;
  77015. this._glowLayer = null;
  77016. }
  77017. };
  77018. /**
  77019. * Adds a camera to the pipeline
  77020. * @param camera the camera to be added
  77021. */
  77022. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  77023. this._camerasToBeAttached.push(camera);
  77024. this._buildPipeline();
  77025. };
  77026. /**
  77027. * Removes a camera from the pipeline
  77028. * @param camera the camera to remove
  77029. */
  77030. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  77031. var index = this._camerasToBeAttached.indexOf(camera);
  77032. this._camerasToBeAttached.splice(index, 1);
  77033. this._buildPipeline();
  77034. };
  77035. /**
  77036. * Dispose of the pipeline and stop all post processes
  77037. */
  77038. DefaultRenderingPipeline.prototype.dispose = function () {
  77039. this._disposePostProcesses(true);
  77040. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77041. this._scene.autoClear = true;
  77042. if (this._resizeObserver) {
  77043. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  77044. this._resizeObserver = null;
  77045. }
  77046. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  77047. _super.prototype.dispose.call(this);
  77048. };
  77049. /**
  77050. * Serialize the rendering pipeline (Used when exporting)
  77051. * @returns the serialized object
  77052. */
  77053. DefaultRenderingPipeline.prototype.serialize = function () {
  77054. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77055. serializationObject.customType = "DefaultRenderingPipeline";
  77056. return serializationObject;
  77057. };
  77058. /**
  77059. * Parse the serialized pipeline
  77060. * @param source Source pipeline.
  77061. * @param scene The scene to load the pipeline to.
  77062. * @param rootUrl The URL of the serialized pipeline.
  77063. * @returns An instantiated pipeline from the serialized object.
  77064. */
  77065. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77066. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  77067. };
  77068. __decorate([
  77069. BABYLON.serialize()
  77070. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  77071. __decorate([
  77072. BABYLON.serialize()
  77073. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  77074. __decorate([
  77075. BABYLON.serialize()
  77076. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  77077. __decorate([
  77078. BABYLON.serialize()
  77079. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  77080. __decorate([
  77081. BABYLON.serialize()
  77082. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  77083. __decorate([
  77084. BABYLON.serialize()
  77085. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  77086. __decorate([
  77087. BABYLON.serialize()
  77088. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  77089. __decorate([
  77090. BABYLON.serialize()
  77091. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  77092. __decorate([
  77093. BABYLON.serialize()
  77094. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  77095. __decorate([
  77096. BABYLON.serialize()
  77097. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  77098. __decorate([
  77099. BABYLON.serialize()
  77100. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  77101. __decorate([
  77102. BABYLON.serialize()
  77103. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  77104. __decorate([
  77105. BABYLON.serialize()
  77106. ], DefaultRenderingPipeline.prototype, "samples", null);
  77107. __decorate([
  77108. BABYLON.serialize()
  77109. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  77110. __decorate([
  77111. BABYLON.serialize()
  77112. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  77113. __decorate([
  77114. BABYLON.serialize()
  77115. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  77116. __decorate([
  77117. BABYLON.serialize()
  77118. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  77119. return DefaultRenderingPipeline;
  77120. }(BABYLON.PostProcessRenderPipeline));
  77121. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  77122. })(BABYLON || (BABYLON = {}));
  77123. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  77124. var BABYLON;
  77125. (function (BABYLON) {
  77126. /**
  77127. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77128. */
  77129. var GeometryBufferRenderer = /** @class */ (function () {
  77130. /**
  77131. * Creates a new G Buffer for the scene
  77132. * @param scene The scene the buffer belongs to
  77133. * @param ratio How big is the buffer related to the main canvas.
  77134. */
  77135. function GeometryBufferRenderer(scene, ratio) {
  77136. if (ratio === void 0) { ratio = 1; }
  77137. this._enablePosition = false;
  77138. this._scene = scene;
  77139. this._ratio = ratio;
  77140. // Render target
  77141. this._createRenderTargets();
  77142. }
  77143. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77144. /**
  77145. * Set the render list (meshes to be rendered) used in the G buffer.
  77146. */
  77147. set: function (meshes) {
  77148. this._multiRenderTarget.renderList = meshes;
  77149. },
  77150. enumerable: true,
  77151. configurable: true
  77152. });
  77153. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77154. /**
  77155. * Gets wether or not G buffer are supported by the running hardware.
  77156. * This requires draw buffer supports
  77157. */
  77158. get: function () {
  77159. return this._multiRenderTarget.isSupported;
  77160. },
  77161. enumerable: true,
  77162. configurable: true
  77163. });
  77164. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77165. /**
  77166. * Gets wether or not position are enabled for the G buffer.
  77167. */
  77168. get: function () {
  77169. return this._enablePosition;
  77170. },
  77171. /**
  77172. * Sets wether or not position are enabled for the G buffer.
  77173. */
  77174. set: function (enable) {
  77175. this._enablePosition = enable;
  77176. this.dispose();
  77177. this._createRenderTargets();
  77178. },
  77179. enumerable: true,
  77180. configurable: true
  77181. });
  77182. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77183. /**
  77184. * Gets the scene associated with the buffer.
  77185. */
  77186. get: function () {
  77187. return this._scene;
  77188. },
  77189. enumerable: true,
  77190. configurable: true
  77191. });
  77192. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77193. /**
  77194. * Gets the ratio used by the buffer during its creation.
  77195. * How big is the buffer related to the main canvas.
  77196. */
  77197. get: function () {
  77198. return this._ratio;
  77199. },
  77200. enumerable: true,
  77201. configurable: true
  77202. });
  77203. /**
  77204. * Checks wether everything is ready to render a submesh to the G buffer.
  77205. * @param subMesh the submesh to check readiness for
  77206. * @param useInstances is the mesh drawn using instance or not
  77207. * @returns true if ready otherwise false
  77208. */
  77209. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77210. var material = subMesh.getMaterial();
  77211. if (material && material.disableDepthWrite) {
  77212. return false;
  77213. }
  77214. var defines = [];
  77215. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77216. var mesh = subMesh.getMesh();
  77217. // Alpha test
  77218. if (material && material.needAlphaTesting()) {
  77219. defines.push("#define ALPHATEST");
  77220. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77221. attribs.push(BABYLON.VertexBuffer.UVKind);
  77222. defines.push("#define UV1");
  77223. }
  77224. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77225. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77226. defines.push("#define UV2");
  77227. }
  77228. }
  77229. // Buffers
  77230. if (this._enablePosition) {
  77231. defines.push("#define POSITION");
  77232. }
  77233. // Bones
  77234. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77235. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77236. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77237. if (mesh.numBoneInfluencers > 4) {
  77238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77240. }
  77241. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77242. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77243. }
  77244. else {
  77245. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77246. }
  77247. // Instances
  77248. if (useInstances) {
  77249. defines.push("#define INSTANCES");
  77250. attribs.push("world0");
  77251. attribs.push("world1");
  77252. attribs.push("world2");
  77253. attribs.push("world3");
  77254. }
  77255. // Get correct effect
  77256. var join = defines.join("\n");
  77257. if (this._cachedDefines !== join) {
  77258. this._cachedDefines = join;
  77259. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77260. }
  77261. return this._effect.isReady();
  77262. };
  77263. /**
  77264. * Gets the current underlying G Buffer.
  77265. * @returns the buffer
  77266. */
  77267. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77268. return this._multiRenderTarget;
  77269. };
  77270. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77271. /**
  77272. * Gets the number of samples used to render the buffer (anti aliasing).
  77273. */
  77274. get: function () {
  77275. return this._multiRenderTarget.samples;
  77276. },
  77277. /**
  77278. * Sets the number of samples used to render the buffer (anti aliasing).
  77279. */
  77280. set: function (value) {
  77281. this._multiRenderTarget.samples = value;
  77282. },
  77283. enumerable: true,
  77284. configurable: true
  77285. });
  77286. /**
  77287. * Disposes the renderer and frees up associated resources.
  77288. */
  77289. GeometryBufferRenderer.prototype.dispose = function () {
  77290. this.getGBuffer().dispose();
  77291. };
  77292. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77293. var _this = this;
  77294. var engine = this._scene.getEngine();
  77295. var count = this._enablePosition ? 3 : 2;
  77296. 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 });
  77297. if (!this.isSupported) {
  77298. return;
  77299. }
  77300. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77301. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77302. this._multiRenderTarget.refreshRate = 1;
  77303. this._multiRenderTarget.renderParticles = false;
  77304. this._multiRenderTarget.renderList = null;
  77305. // set default depth value to 1.0 (far away)
  77306. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77307. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77308. });
  77309. // Custom render function
  77310. var renderSubMesh = function (subMesh) {
  77311. var mesh = subMesh.getRenderingMesh();
  77312. var scene = _this._scene;
  77313. var engine = scene.getEngine();
  77314. var material = subMesh.getMaterial();
  77315. if (!material) {
  77316. return;
  77317. }
  77318. // Culling
  77319. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77320. // Managing instances
  77321. var batch = mesh._getInstancesRenderList(subMesh._id);
  77322. if (batch.mustReturn) {
  77323. return;
  77324. }
  77325. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77326. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77327. engine.enableEffect(_this._effect);
  77328. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77329. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77330. _this._effect.setMatrix("view", scene.getViewMatrix());
  77331. // Alpha test
  77332. if (material && material.needAlphaTesting()) {
  77333. var alphaTexture = material.getAlphaTestTexture();
  77334. if (alphaTexture) {
  77335. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77336. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77337. }
  77338. }
  77339. // Bones
  77340. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77341. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77342. }
  77343. // Draw
  77344. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77345. }
  77346. };
  77347. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77348. var index;
  77349. if (depthOnlySubMeshes.length) {
  77350. engine.setColorWrite(false);
  77351. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77352. renderSubMesh(depthOnlySubMeshes.data[index]);
  77353. }
  77354. engine.setColorWrite(true);
  77355. }
  77356. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77357. renderSubMesh(opaqueSubMeshes.data[index]);
  77358. }
  77359. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77360. renderSubMesh(alphaTestSubMeshes.data[index]);
  77361. }
  77362. };
  77363. };
  77364. return GeometryBufferRenderer;
  77365. }());
  77366. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77367. })(BABYLON || (BABYLON = {}));
  77368. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77369. var BABYLON;
  77370. (function (BABYLON) {
  77371. /**
  77372. * This groups together the common properties used for image processing either in direct forward pass
  77373. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77374. * or not.
  77375. */
  77376. var ImageProcessingConfiguration = /** @class */ (function () {
  77377. function ImageProcessingConfiguration() {
  77378. /**
  77379. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77380. */
  77381. this.colorCurves = new BABYLON.ColorCurves();
  77382. this._colorCurvesEnabled = false;
  77383. this._colorGradingEnabled = false;
  77384. this._colorGradingWithGreenDepth = true;
  77385. this._colorGradingBGR = true;
  77386. this._exposure = 1.0;
  77387. this._toneMappingEnabled = false;
  77388. this._contrast = 1.0;
  77389. /**
  77390. * Vignette stretch size.
  77391. */
  77392. this.vignetteStretch = 0;
  77393. /**
  77394. * Vignette centre X Offset.
  77395. */
  77396. this.vignetteCentreX = 0;
  77397. /**
  77398. * Vignette centre Y Offset.
  77399. */
  77400. this.vignetteCentreY = 0;
  77401. /**
  77402. * Vignette weight or intensity of the vignette effect.
  77403. */
  77404. this.vignetteWeight = 1.5;
  77405. /**
  77406. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77407. * if vignetteEnabled is set to true.
  77408. */
  77409. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77410. /**
  77411. * Camera field of view used by the Vignette effect.
  77412. */
  77413. this.vignetteCameraFov = 0.5;
  77414. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77415. this._vignetteEnabled = false;
  77416. this._applyByPostProcess = false;
  77417. this._isEnabled = true;
  77418. /**
  77419. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77420. */
  77421. this.onUpdateParameters = new BABYLON.Observable();
  77422. }
  77423. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77424. /**
  77425. * Gets wether the color curves effect is enabled.
  77426. */
  77427. get: function () {
  77428. return this._colorCurvesEnabled;
  77429. },
  77430. /**
  77431. * Sets wether the color curves effect is enabled.
  77432. */
  77433. set: function (value) {
  77434. if (this._colorCurvesEnabled === value) {
  77435. return;
  77436. }
  77437. this._colorCurvesEnabled = value;
  77438. this._updateParameters();
  77439. },
  77440. enumerable: true,
  77441. configurable: true
  77442. });
  77443. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77444. /**
  77445. * Gets wether the color grading effect is enabled.
  77446. */
  77447. get: function () {
  77448. return this._colorGradingEnabled;
  77449. },
  77450. /**
  77451. * Sets wether the color grading effect is enabled.
  77452. */
  77453. set: function (value) {
  77454. if (this._colorGradingEnabled === value) {
  77455. return;
  77456. }
  77457. this._colorGradingEnabled = value;
  77458. this._updateParameters();
  77459. },
  77460. enumerable: true,
  77461. configurable: true
  77462. });
  77463. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77464. /**
  77465. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77466. */
  77467. get: function () {
  77468. return this._colorGradingWithGreenDepth;
  77469. },
  77470. /**
  77471. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77472. */
  77473. set: function (value) {
  77474. if (this._colorGradingWithGreenDepth === value) {
  77475. return;
  77476. }
  77477. this._colorGradingWithGreenDepth = value;
  77478. this._updateParameters();
  77479. },
  77480. enumerable: true,
  77481. configurable: true
  77482. });
  77483. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77484. /**
  77485. * Gets wether the color grading texture contains BGR values.
  77486. */
  77487. get: function () {
  77488. return this._colorGradingBGR;
  77489. },
  77490. /**
  77491. * Sets wether the color grading texture contains BGR values.
  77492. */
  77493. set: function (value) {
  77494. if (this._colorGradingBGR === value) {
  77495. return;
  77496. }
  77497. this._colorGradingBGR = value;
  77498. this._updateParameters();
  77499. },
  77500. enumerable: true,
  77501. configurable: true
  77502. });
  77503. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77504. /**
  77505. * Gets the Exposure used in the effect.
  77506. */
  77507. get: function () {
  77508. return this._exposure;
  77509. },
  77510. /**
  77511. * Sets the Exposure used in the effect.
  77512. */
  77513. set: function (value) {
  77514. if (this._exposure === value) {
  77515. return;
  77516. }
  77517. this._exposure = value;
  77518. this._updateParameters();
  77519. },
  77520. enumerable: true,
  77521. configurable: true
  77522. });
  77523. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77524. /**
  77525. * Gets wether the tone mapping effect is enabled.
  77526. */
  77527. get: function () {
  77528. return this._toneMappingEnabled;
  77529. },
  77530. /**
  77531. * Sets wether the tone mapping effect is enabled.
  77532. */
  77533. set: function (value) {
  77534. if (this._toneMappingEnabled === value) {
  77535. return;
  77536. }
  77537. this._toneMappingEnabled = value;
  77538. this._updateParameters();
  77539. },
  77540. enumerable: true,
  77541. configurable: true
  77542. });
  77543. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77544. /**
  77545. * Gets the contrast used in the effect.
  77546. */
  77547. get: function () {
  77548. return this._contrast;
  77549. },
  77550. /**
  77551. * Sets the contrast used in the effect.
  77552. */
  77553. set: function (value) {
  77554. if (this._contrast === value) {
  77555. return;
  77556. }
  77557. this._contrast = value;
  77558. this._updateParameters();
  77559. },
  77560. enumerable: true,
  77561. configurable: true
  77562. });
  77563. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77564. /**
  77565. * Gets the vignette blend mode allowing different kind of effect.
  77566. */
  77567. get: function () {
  77568. return this._vignetteBlendMode;
  77569. },
  77570. /**
  77571. * Sets the vignette blend mode allowing different kind of effect.
  77572. */
  77573. set: function (value) {
  77574. if (this._vignetteBlendMode === value) {
  77575. return;
  77576. }
  77577. this._vignetteBlendMode = value;
  77578. this._updateParameters();
  77579. },
  77580. enumerable: true,
  77581. configurable: true
  77582. });
  77583. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77584. /**
  77585. * Gets wether the vignette effect is enabled.
  77586. */
  77587. get: function () {
  77588. return this._vignetteEnabled;
  77589. },
  77590. /**
  77591. * Sets wether the vignette effect is enabled.
  77592. */
  77593. set: function (value) {
  77594. if (this._vignetteEnabled === value) {
  77595. return;
  77596. }
  77597. this._vignetteEnabled = value;
  77598. this._updateParameters();
  77599. },
  77600. enumerable: true,
  77601. configurable: true
  77602. });
  77603. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77604. /**
  77605. * Gets wether the image processing is applied through a post process or not.
  77606. */
  77607. get: function () {
  77608. return this._applyByPostProcess;
  77609. },
  77610. /**
  77611. * Sets wether the image processing is applied through a post process or not.
  77612. */
  77613. set: function (value) {
  77614. if (this._applyByPostProcess === value) {
  77615. return;
  77616. }
  77617. this._applyByPostProcess = value;
  77618. this._updateParameters();
  77619. },
  77620. enumerable: true,
  77621. configurable: true
  77622. });
  77623. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77624. /**
  77625. * Gets wether the image processing is enabled or not.
  77626. */
  77627. get: function () {
  77628. return this._isEnabled;
  77629. },
  77630. /**
  77631. * Sets wether the image processing is enabled or not.
  77632. */
  77633. set: function (value) {
  77634. if (this._isEnabled === value) {
  77635. return;
  77636. }
  77637. this._isEnabled = value;
  77638. this._updateParameters();
  77639. },
  77640. enumerable: true,
  77641. configurable: true
  77642. });
  77643. /**
  77644. * Method called each time the image processing information changes requires to recompile the effect.
  77645. */
  77646. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77647. this.onUpdateParameters.notifyObservers(this);
  77648. };
  77649. ImageProcessingConfiguration.prototype.getClassName = function () {
  77650. return "ImageProcessingConfiguration";
  77651. };
  77652. /**
  77653. * Prepare the list of uniforms associated with the Image Processing effects.
  77654. * @param uniformsList The list of uniforms used in the effect
  77655. * @param defines the list of defines currently in use
  77656. */
  77657. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77658. if (defines.EXPOSURE) {
  77659. uniforms.push("exposureLinear");
  77660. }
  77661. if (defines.CONTRAST) {
  77662. uniforms.push("contrast");
  77663. }
  77664. if (defines.COLORGRADING) {
  77665. uniforms.push("colorTransformSettings");
  77666. }
  77667. if (defines.VIGNETTE) {
  77668. uniforms.push("vInverseScreenSize");
  77669. uniforms.push("vignetteSettings1");
  77670. uniforms.push("vignetteSettings2");
  77671. }
  77672. if (defines.COLORCURVES) {
  77673. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77674. }
  77675. };
  77676. /**
  77677. * Prepare the list of samplers associated with the Image Processing effects.
  77678. * @param uniformsList The list of uniforms used in the effect
  77679. * @param defines the list of defines currently in use
  77680. */
  77681. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77682. if (defines.COLORGRADING) {
  77683. samplersList.push("txColorTransform");
  77684. }
  77685. };
  77686. /**
  77687. * Prepare the list of defines associated to the shader.
  77688. * @param defines the list of defines to complete
  77689. */
  77690. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77691. if (forPostProcess === void 0) { forPostProcess = false; }
  77692. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77693. defines.VIGNETTE = false;
  77694. defines.TONEMAPPING = false;
  77695. defines.CONTRAST = false;
  77696. defines.EXPOSURE = false;
  77697. defines.COLORCURVES = false;
  77698. defines.COLORGRADING = false;
  77699. defines.COLORGRADING3D = false;
  77700. defines.IMAGEPROCESSING = false;
  77701. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77702. return;
  77703. }
  77704. defines.VIGNETTE = this.vignetteEnabled;
  77705. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77706. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77707. defines.TONEMAPPING = this.toneMappingEnabled;
  77708. defines.CONTRAST = (this.contrast !== 1.0);
  77709. defines.EXPOSURE = (this.exposure !== 1.0);
  77710. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77711. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77712. if (defines.COLORGRADING) {
  77713. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77714. }
  77715. else {
  77716. defines.COLORGRADING3D = false;
  77717. }
  77718. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77719. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77720. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77721. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77722. };
  77723. /**
  77724. * Returns true if all the image processing information are ready.
  77725. */
  77726. ImageProcessingConfiguration.prototype.isReady = function () {
  77727. // Color Grading texure can not be none blocking.
  77728. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77729. };
  77730. /**
  77731. * Binds the image processing to the shader.
  77732. * @param effect The effect to bind to
  77733. */
  77734. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77735. if (aspectRatio === void 0) { aspectRatio = 1; }
  77736. // Color Curves
  77737. if (this._colorCurvesEnabled && this.colorCurves) {
  77738. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77739. }
  77740. // Vignette
  77741. if (this._vignetteEnabled) {
  77742. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77743. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77744. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77745. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77746. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77747. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77748. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77749. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77750. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77751. var vignettePower = -2.0 * this.vignetteWeight;
  77752. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77753. }
  77754. // Exposure
  77755. effect.setFloat("exposureLinear", this.exposure);
  77756. // Contrast
  77757. effect.setFloat("contrast", this.contrast);
  77758. // Color transform settings
  77759. if (this.colorGradingTexture) {
  77760. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77761. var textureSize = this.colorGradingTexture.getSize().height;
  77762. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77763. 0.5 / textureSize, // textureOffset
  77764. textureSize, // textureSize
  77765. this.colorGradingTexture.level // weight
  77766. );
  77767. }
  77768. };
  77769. /**
  77770. * Clones the current image processing instance.
  77771. * @return The cloned image processing
  77772. */
  77773. ImageProcessingConfiguration.prototype.clone = function () {
  77774. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77775. };
  77776. /**
  77777. * Serializes the current image processing instance to a json representation.
  77778. * @return a JSON representation
  77779. */
  77780. ImageProcessingConfiguration.prototype.serialize = function () {
  77781. return BABYLON.SerializationHelper.Serialize(this);
  77782. };
  77783. /**
  77784. * Parses the image processing from a json representation.
  77785. * @param source the JSON source to parse
  77786. * @return The parsed image processing
  77787. */
  77788. ImageProcessingConfiguration.Parse = function (source) {
  77789. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77790. };
  77791. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77792. /**
  77793. * Used to apply the vignette as a mix with the pixel color.
  77794. */
  77795. get: function () {
  77796. return this._VIGNETTEMODE_MULTIPLY;
  77797. },
  77798. enumerable: true,
  77799. configurable: true
  77800. });
  77801. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77802. /**
  77803. * Used to apply the vignette as a replacement of the pixel color.
  77804. */
  77805. get: function () {
  77806. return this._VIGNETTEMODE_OPAQUE;
  77807. },
  77808. enumerable: true,
  77809. configurable: true
  77810. });
  77811. // Static constants associated to the image processing.
  77812. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77813. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77814. __decorate([
  77815. BABYLON.serializeAsColorCurves()
  77816. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77817. __decorate([
  77818. BABYLON.serialize()
  77819. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77820. __decorate([
  77821. BABYLON.serializeAsTexture()
  77822. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77823. __decorate([
  77824. BABYLON.serialize()
  77825. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77826. __decorate([
  77827. BABYLON.serialize()
  77828. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77829. __decorate([
  77830. BABYLON.serialize()
  77831. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77832. __decorate([
  77833. BABYLON.serialize()
  77834. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77835. __decorate([
  77836. BABYLON.serialize()
  77837. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77838. __decorate([
  77839. BABYLON.serialize()
  77840. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77841. __decorate([
  77842. BABYLON.serialize()
  77843. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77844. __decorate([
  77845. BABYLON.serialize()
  77846. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77847. __decorate([
  77848. BABYLON.serialize()
  77849. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77850. __decorate([
  77851. BABYLON.serialize()
  77852. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77853. __decorate([
  77854. BABYLON.serializeAsColor4()
  77855. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77856. __decorate([
  77857. BABYLON.serialize()
  77858. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77859. __decorate([
  77860. BABYLON.serialize()
  77861. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77862. __decorate([
  77863. BABYLON.serialize()
  77864. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77865. __decorate([
  77866. BABYLON.serialize()
  77867. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77868. __decorate([
  77869. BABYLON.serialize()
  77870. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77871. return ImageProcessingConfiguration;
  77872. }());
  77873. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77874. })(BABYLON || (BABYLON = {}));
  77875. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77876. var BABYLON;
  77877. (function (BABYLON) {
  77878. /**
  77879. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77880. * It can help converting any input color in a desired output one. This can then be used to create effects
  77881. * from sepia, black and white to sixties or futuristic rendering...
  77882. *
  77883. * The only supported format is currently 3dl.
  77884. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77885. */
  77886. var ColorGradingTexture = /** @class */ (function (_super) {
  77887. __extends(ColorGradingTexture, _super);
  77888. /**
  77889. * Instantiates a ColorGradingTexture from the following parameters.
  77890. *
  77891. * @param url The location of the color gradind data (currently only supporting 3dl)
  77892. * @param scene The scene the texture will be used in
  77893. */
  77894. function ColorGradingTexture(url, scene) {
  77895. var _this = _super.call(this, scene) || this;
  77896. if (!url) {
  77897. return _this;
  77898. }
  77899. _this._engine = scene.getEngine();
  77900. _this._textureMatrix = BABYLON.Matrix.Identity();
  77901. _this.name = url;
  77902. _this.url = url;
  77903. _this.hasAlpha = false;
  77904. _this.isCube = false;
  77905. _this.is3D = _this._engine.webGLVersion > 1;
  77906. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77907. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77908. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77909. _this.anisotropicFilteringLevel = 1;
  77910. _this._texture = _this._getFromCache(url, true);
  77911. if (!_this._texture) {
  77912. if (!scene.useDelayedTextureLoading) {
  77913. _this.loadTexture();
  77914. }
  77915. else {
  77916. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77917. }
  77918. }
  77919. return _this;
  77920. }
  77921. /**
  77922. * Returns the texture matrix used in most of the material.
  77923. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77924. */
  77925. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77926. return this._textureMatrix;
  77927. };
  77928. /**
  77929. * Occurs when the file being loaded is a .3dl LUT file.
  77930. */
  77931. ColorGradingTexture.prototype.load3dlTexture = function () {
  77932. var engine = this._engine;
  77933. var texture;
  77934. if (engine.webGLVersion === 1) {
  77935. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77936. }
  77937. else {
  77938. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77939. }
  77940. this._texture = texture;
  77941. var callback = function (text) {
  77942. if (typeof text !== "string") {
  77943. return;
  77944. }
  77945. var data = null;
  77946. var tempData = null;
  77947. var line;
  77948. var lines = text.split('\n');
  77949. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77950. var maxColor = 0;
  77951. for (var i = 0; i < lines.length; i++) {
  77952. line = lines[i];
  77953. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77954. continue;
  77955. if (line.indexOf('#') === 0)
  77956. continue;
  77957. var words = line.split(" ");
  77958. if (size === 0) {
  77959. // Number of space + one
  77960. size = words.length;
  77961. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77962. tempData = new Float32Array(size * size * size * 4);
  77963. continue;
  77964. }
  77965. if (size != 0) {
  77966. var r = Math.max(parseInt(words[0]), 0);
  77967. var g = Math.max(parseInt(words[1]), 0);
  77968. var b = Math.max(parseInt(words[2]), 0);
  77969. maxColor = Math.max(r, maxColor);
  77970. maxColor = Math.max(g, maxColor);
  77971. maxColor = Math.max(b, maxColor);
  77972. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77973. if (tempData) {
  77974. tempData[pixelStorageIndex + 0] = r;
  77975. tempData[pixelStorageIndex + 1] = g;
  77976. tempData[pixelStorageIndex + 2] = b;
  77977. }
  77978. pixelIndexSlice++;
  77979. if (pixelIndexSlice % size == 0) {
  77980. pixelIndexH++;
  77981. pixelIndexSlice = 0;
  77982. if (pixelIndexH % size == 0) {
  77983. pixelIndexW++;
  77984. pixelIndexH = 0;
  77985. }
  77986. }
  77987. }
  77988. }
  77989. if (tempData && data) {
  77990. for (var i = 0; i < tempData.length; i++) {
  77991. if (i > 0 && (i + 1) % 4 === 0) {
  77992. data[i] = 255;
  77993. }
  77994. else {
  77995. var value = tempData[i];
  77996. data[i] = (value / maxColor * 255);
  77997. }
  77998. }
  77999. }
  78000. if (texture.is3D) {
  78001. texture.updateSize(size, size, size);
  78002. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78003. }
  78004. else {
  78005. texture.updateSize(size * size, size);
  78006. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78007. }
  78008. };
  78009. var scene = this.getScene();
  78010. if (scene) {
  78011. scene._loadFile(this.url, callback);
  78012. }
  78013. else {
  78014. this._engine._loadFile(this.url, callback);
  78015. }
  78016. return this._texture;
  78017. };
  78018. /**
  78019. * Starts the loading process of the texture.
  78020. */
  78021. ColorGradingTexture.prototype.loadTexture = function () {
  78022. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  78023. this.load3dlTexture();
  78024. }
  78025. };
  78026. /**
  78027. * Clones the color gradind texture.
  78028. */
  78029. ColorGradingTexture.prototype.clone = function () {
  78030. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  78031. // Base texture
  78032. newTexture.level = this.level;
  78033. return newTexture;
  78034. };
  78035. /**
  78036. * Called during delayed load for textures.
  78037. */
  78038. ColorGradingTexture.prototype.delayLoad = function () {
  78039. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78040. return;
  78041. }
  78042. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78043. this._texture = this._getFromCache(this.url, true);
  78044. if (!this._texture) {
  78045. this.loadTexture();
  78046. }
  78047. };
  78048. /**
  78049. * Parses a color grading texture serialized by Babylon.
  78050. * @param parsedTexture The texture information being parsedTexture
  78051. * @param scene The scene to load the texture in
  78052. * @param rootUrl The root url of the data assets to load
  78053. * @return A color gradind texture
  78054. */
  78055. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78056. var texture = null;
  78057. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78058. texture = new ColorGradingTexture(parsedTexture.name, scene);
  78059. texture.name = parsedTexture.name;
  78060. texture.level = parsedTexture.level;
  78061. }
  78062. return texture;
  78063. };
  78064. /**
  78065. * Serializes the LUT texture to json format.
  78066. */
  78067. ColorGradingTexture.prototype.serialize = function () {
  78068. if (!this.name) {
  78069. return null;
  78070. }
  78071. var serializationObject = {};
  78072. serializationObject.name = this.name;
  78073. serializationObject.level = this.level;
  78074. serializationObject.customType = "BABYLON.ColorGradingTexture";
  78075. return serializationObject;
  78076. };
  78077. /**
  78078. * Empty line regex stored for GC.
  78079. */
  78080. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  78081. return ColorGradingTexture;
  78082. }(BABYLON.BaseTexture));
  78083. BABYLON.ColorGradingTexture = ColorGradingTexture;
  78084. })(BABYLON || (BABYLON = {}));
  78085. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  78086. var BABYLON;
  78087. (function (BABYLON) {
  78088. /**
  78089. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78090. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78091. * 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;
  78092. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78093. */
  78094. var ColorCurves = /** @class */ (function () {
  78095. function ColorCurves() {
  78096. this._dirty = true;
  78097. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  78098. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  78099. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78100. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  78101. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78102. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  78103. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  78104. this._globalHue = 30;
  78105. this._globalDensity = 0;
  78106. this._globalSaturation = 0;
  78107. this._globalExposure = 0;
  78108. this._highlightsHue = 30;
  78109. this._highlightsDensity = 0;
  78110. this._highlightsSaturation = 0;
  78111. this._highlightsExposure = 0;
  78112. this._midtonesHue = 30;
  78113. this._midtonesDensity = 0;
  78114. this._midtonesSaturation = 0;
  78115. this._midtonesExposure = 0;
  78116. this._shadowsHue = 30;
  78117. this._shadowsDensity = 0;
  78118. this._shadowsSaturation = 0;
  78119. this._shadowsExposure = 0;
  78120. }
  78121. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  78122. /**
  78123. * Gets the global Hue value.
  78124. * 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).
  78125. */
  78126. get: function () {
  78127. return this._globalHue;
  78128. },
  78129. /**
  78130. * Sets the global Hue value.
  78131. * 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).
  78132. */
  78133. set: function (value) {
  78134. this._globalHue = value;
  78135. this._dirty = true;
  78136. },
  78137. enumerable: true,
  78138. configurable: true
  78139. });
  78140. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  78141. /**
  78142. * Gets the global Density value.
  78143. * 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.
  78144. * Values less than zero provide a filter of opposite hue.
  78145. */
  78146. get: function () {
  78147. return this._globalDensity;
  78148. },
  78149. /**
  78150. * Sets the global Density value.
  78151. * 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.
  78152. * Values less than zero provide a filter of opposite hue.
  78153. */
  78154. set: function (value) {
  78155. this._globalDensity = value;
  78156. this._dirty = true;
  78157. },
  78158. enumerable: true,
  78159. configurable: true
  78160. });
  78161. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  78162. /**
  78163. * Gets the global Saturation value.
  78164. * 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.
  78165. */
  78166. get: function () {
  78167. return this._globalSaturation;
  78168. },
  78169. /**
  78170. * Sets the global Saturation value.
  78171. * 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.
  78172. */
  78173. set: function (value) {
  78174. this._globalSaturation = value;
  78175. this._dirty = true;
  78176. },
  78177. enumerable: true,
  78178. configurable: true
  78179. });
  78180. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  78181. /**
  78182. * Gets the global Exposure value.
  78183. * 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.
  78184. */
  78185. get: function () {
  78186. return this._globalExposure;
  78187. },
  78188. /**
  78189. * Sets the global Exposure value.
  78190. * 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.
  78191. */
  78192. set: function (value) {
  78193. this._globalExposure = value;
  78194. this._dirty = true;
  78195. },
  78196. enumerable: true,
  78197. configurable: true
  78198. });
  78199. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  78200. /**
  78201. * Gets the highlights Hue value.
  78202. * 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).
  78203. */
  78204. get: function () {
  78205. return this._highlightsHue;
  78206. },
  78207. /**
  78208. * Sets the highlights Hue value.
  78209. * 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).
  78210. */
  78211. set: function (value) {
  78212. this._highlightsHue = value;
  78213. this._dirty = true;
  78214. },
  78215. enumerable: true,
  78216. configurable: true
  78217. });
  78218. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  78219. /**
  78220. * Gets the highlights Density value.
  78221. * 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.
  78222. * Values less than zero provide a filter of opposite hue.
  78223. */
  78224. get: function () {
  78225. return this._highlightsDensity;
  78226. },
  78227. /**
  78228. * Sets the highlights Density value.
  78229. * 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.
  78230. * Values less than zero provide a filter of opposite hue.
  78231. */
  78232. set: function (value) {
  78233. this._highlightsDensity = value;
  78234. this._dirty = true;
  78235. },
  78236. enumerable: true,
  78237. configurable: true
  78238. });
  78239. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  78240. /**
  78241. * Gets the highlights Saturation value.
  78242. * 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.
  78243. */
  78244. get: function () {
  78245. return this._highlightsSaturation;
  78246. },
  78247. /**
  78248. * Sets the highlights Saturation value.
  78249. * 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.
  78250. */
  78251. set: function (value) {
  78252. this._highlightsSaturation = value;
  78253. this._dirty = true;
  78254. },
  78255. enumerable: true,
  78256. configurable: true
  78257. });
  78258. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78259. /**
  78260. * Gets the highlights Exposure value.
  78261. * 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.
  78262. */
  78263. get: function () {
  78264. return this._highlightsExposure;
  78265. },
  78266. /**
  78267. * Sets the highlights Exposure value.
  78268. * 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.
  78269. */
  78270. set: function (value) {
  78271. this._highlightsExposure = value;
  78272. this._dirty = true;
  78273. },
  78274. enumerable: true,
  78275. configurable: true
  78276. });
  78277. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78278. /**
  78279. * Gets the midtones Hue value.
  78280. * 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).
  78281. */
  78282. get: function () {
  78283. return this._midtonesHue;
  78284. },
  78285. /**
  78286. * Sets the midtones Hue value.
  78287. * 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).
  78288. */
  78289. set: function (value) {
  78290. this._midtonesHue = value;
  78291. this._dirty = true;
  78292. },
  78293. enumerable: true,
  78294. configurable: true
  78295. });
  78296. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78297. /**
  78298. * Gets the midtones Density value.
  78299. * 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.
  78300. * Values less than zero provide a filter of opposite hue.
  78301. */
  78302. get: function () {
  78303. return this._midtonesDensity;
  78304. },
  78305. /**
  78306. * Sets the midtones Density value.
  78307. * 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.
  78308. * Values less than zero provide a filter of opposite hue.
  78309. */
  78310. set: function (value) {
  78311. this._midtonesDensity = value;
  78312. this._dirty = true;
  78313. },
  78314. enumerable: true,
  78315. configurable: true
  78316. });
  78317. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78318. /**
  78319. * Gets the midtones Saturation value.
  78320. * 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.
  78321. */
  78322. get: function () {
  78323. return this._midtonesSaturation;
  78324. },
  78325. /**
  78326. * Sets the midtones Saturation value.
  78327. * 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.
  78328. */
  78329. set: function (value) {
  78330. this._midtonesSaturation = value;
  78331. this._dirty = true;
  78332. },
  78333. enumerable: true,
  78334. configurable: true
  78335. });
  78336. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78337. /**
  78338. * Gets the midtones Exposure value.
  78339. * 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.
  78340. */
  78341. get: function () {
  78342. return this._midtonesExposure;
  78343. },
  78344. /**
  78345. * Sets the midtones Exposure value.
  78346. * 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.
  78347. */
  78348. set: function (value) {
  78349. this._midtonesExposure = value;
  78350. this._dirty = true;
  78351. },
  78352. enumerable: true,
  78353. configurable: true
  78354. });
  78355. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78356. /**
  78357. * Gets the shadows Hue value.
  78358. * 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).
  78359. */
  78360. get: function () {
  78361. return this._shadowsHue;
  78362. },
  78363. /**
  78364. * Sets the shadows Hue value.
  78365. * 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).
  78366. */
  78367. set: function (value) {
  78368. this._shadowsHue = value;
  78369. this._dirty = true;
  78370. },
  78371. enumerable: true,
  78372. configurable: true
  78373. });
  78374. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78375. /**
  78376. * Gets the shadows Density value.
  78377. * 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.
  78378. * Values less than zero provide a filter of opposite hue.
  78379. */
  78380. get: function () {
  78381. return this._shadowsDensity;
  78382. },
  78383. /**
  78384. * Sets the shadows Density value.
  78385. * 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.
  78386. * Values less than zero provide a filter of opposite hue.
  78387. */
  78388. set: function (value) {
  78389. this._shadowsDensity = value;
  78390. this._dirty = true;
  78391. },
  78392. enumerable: true,
  78393. configurable: true
  78394. });
  78395. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78396. /**
  78397. * Gets the shadows Saturation value.
  78398. * 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.
  78399. */
  78400. get: function () {
  78401. return this._shadowsSaturation;
  78402. },
  78403. /**
  78404. * Sets the shadows Saturation value.
  78405. * 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.
  78406. */
  78407. set: function (value) {
  78408. this._shadowsSaturation = value;
  78409. this._dirty = true;
  78410. },
  78411. enumerable: true,
  78412. configurable: true
  78413. });
  78414. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78415. /**
  78416. * Gets the shadows Exposure value.
  78417. * 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.
  78418. */
  78419. get: function () {
  78420. return this._shadowsExposure;
  78421. },
  78422. /**
  78423. * Sets the shadows Exposure value.
  78424. * 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.
  78425. */
  78426. set: function (value) {
  78427. this._shadowsExposure = value;
  78428. this._dirty = true;
  78429. },
  78430. enumerable: true,
  78431. configurable: true
  78432. });
  78433. ColorCurves.prototype.getClassName = function () {
  78434. return "ColorCurves";
  78435. };
  78436. /**
  78437. * Binds the color curves to the shader.
  78438. * @param colorCurves The color curve to bind
  78439. * @param effect The effect to bind to
  78440. */
  78441. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78442. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78443. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78444. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78445. if (colorCurves._dirty) {
  78446. colorCurves._dirty = false;
  78447. // Fill in global info.
  78448. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78449. // Compute highlights info.
  78450. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78451. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78452. // Compute midtones info.
  78453. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78454. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78455. // Compute shadows info.
  78456. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78457. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78458. // Compute deltas (neutral is midtones).
  78459. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78460. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78461. }
  78462. if (effect) {
  78463. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78464. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78465. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78466. }
  78467. };
  78468. /**
  78469. * Prepare the list of uniforms associated with the ColorCurves effects.
  78470. * @param uniformsList The list of uniforms used in the effect
  78471. */
  78472. ColorCurves.PrepareUniforms = function (uniformsList) {
  78473. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78474. };
  78475. /**
  78476. * Returns color grading data based on a hue, density, saturation and exposure value.
  78477. * @param filterHue The hue of the color filter.
  78478. * @param filterDensity The density of the color filter.
  78479. * @param saturation The saturation.
  78480. * @param exposure The exposure.
  78481. * @param result The result data container.
  78482. */
  78483. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78484. if (hue == null) {
  78485. return;
  78486. }
  78487. hue = ColorCurves.clamp(hue, 0, 360);
  78488. density = ColorCurves.clamp(density, -100, 100);
  78489. saturation = ColorCurves.clamp(saturation, -100, 100);
  78490. exposure = ColorCurves.clamp(exposure, -100, 100);
  78491. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78492. // so that the maximum filter density is only 50% control. This provides fine control
  78493. // for small values and reasonable range.
  78494. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78495. density *= 0.5;
  78496. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78497. if (density < 0) {
  78498. density *= -1;
  78499. hue = (hue + 180) % 360;
  78500. }
  78501. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78502. result.scaleToRef(2, result);
  78503. result.a = 1 + 0.01 * saturation;
  78504. };
  78505. /**
  78506. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78507. * @param value The input slider value in range [-100,100].
  78508. * @returns Adjusted value.
  78509. */
  78510. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78511. value /= 100;
  78512. var x = Math.abs(value);
  78513. x = Math.pow(x, 2);
  78514. if (value < 0) {
  78515. x *= -1;
  78516. }
  78517. x *= 100;
  78518. return x;
  78519. };
  78520. /**
  78521. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78522. * @param hue The hue (H) input.
  78523. * @param saturation The saturation (S) input.
  78524. * @param brightness The brightness (B) input.
  78525. * @result An RGBA color represented as Vector4.
  78526. */
  78527. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78528. var h = ColorCurves.clamp(hue, 0, 360);
  78529. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78530. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78531. if (s === 0) {
  78532. result.r = v;
  78533. result.g = v;
  78534. result.b = v;
  78535. }
  78536. else {
  78537. // sector 0 to 5
  78538. h /= 60;
  78539. var i = Math.floor(h);
  78540. // fractional part of h
  78541. var f = h - i;
  78542. var p = v * (1 - s);
  78543. var q = v * (1 - s * f);
  78544. var t = v * (1 - s * (1 - f));
  78545. switch (i) {
  78546. case 0:
  78547. result.r = v;
  78548. result.g = t;
  78549. result.b = p;
  78550. break;
  78551. case 1:
  78552. result.r = q;
  78553. result.g = v;
  78554. result.b = p;
  78555. break;
  78556. case 2:
  78557. result.r = p;
  78558. result.g = v;
  78559. result.b = t;
  78560. break;
  78561. case 3:
  78562. result.r = p;
  78563. result.g = q;
  78564. result.b = v;
  78565. break;
  78566. case 4:
  78567. result.r = t;
  78568. result.g = p;
  78569. result.b = v;
  78570. break;
  78571. default: // case 5:
  78572. result.r = v;
  78573. result.g = p;
  78574. result.b = q;
  78575. break;
  78576. }
  78577. }
  78578. result.a = 1;
  78579. };
  78580. /**
  78581. * Returns a value clamped between min and max
  78582. * @param value The value to clamp
  78583. * @param min The minimum of value
  78584. * @param max The maximum of value
  78585. * @returns The clamped value.
  78586. */
  78587. ColorCurves.clamp = function (value, min, max) {
  78588. return Math.min(Math.max(value, min), max);
  78589. };
  78590. /**
  78591. * Clones the current color curve instance.
  78592. * @return The cloned curves
  78593. */
  78594. ColorCurves.prototype.clone = function () {
  78595. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78596. };
  78597. /**
  78598. * Serializes the current color curve instance to a json representation.
  78599. * @return a JSON representation
  78600. */
  78601. ColorCurves.prototype.serialize = function () {
  78602. return BABYLON.SerializationHelper.Serialize(this);
  78603. };
  78604. /**
  78605. * Parses the color curve from a json representation.
  78606. * @param source the JSON source to parse
  78607. * @return The parsed curves
  78608. */
  78609. ColorCurves.Parse = function (source) {
  78610. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78611. };
  78612. __decorate([
  78613. BABYLON.serialize()
  78614. ], ColorCurves.prototype, "_globalHue", void 0);
  78615. __decorate([
  78616. BABYLON.serialize()
  78617. ], ColorCurves.prototype, "_globalDensity", void 0);
  78618. __decorate([
  78619. BABYLON.serialize()
  78620. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78621. __decorate([
  78622. BABYLON.serialize()
  78623. ], ColorCurves.prototype, "_globalExposure", void 0);
  78624. __decorate([
  78625. BABYLON.serialize()
  78626. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78627. __decorate([
  78628. BABYLON.serialize()
  78629. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78630. __decorate([
  78631. BABYLON.serialize()
  78632. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78633. __decorate([
  78634. BABYLON.serialize()
  78635. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78636. __decorate([
  78637. BABYLON.serialize()
  78638. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78639. __decorate([
  78640. BABYLON.serialize()
  78641. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78642. __decorate([
  78643. BABYLON.serialize()
  78644. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78645. __decorate([
  78646. BABYLON.serialize()
  78647. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78648. return ColorCurves;
  78649. }());
  78650. BABYLON.ColorCurves = ColorCurves;
  78651. })(BABYLON || (BABYLON = {}));
  78652. //# sourceMappingURL=babylon.colorCurves.js.map
  78653. var BABYLON;
  78654. (function (BABYLON) {
  78655. var RefractionPostProcess = /** @class */ (function (_super) {
  78656. __extends(RefractionPostProcess, _super);
  78657. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78658. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78659. _this.color = color;
  78660. _this.depth = depth;
  78661. _this.colorLevel = colorLevel;
  78662. _this._ownRefractionTexture = true;
  78663. _this.onActivateObservable.add(function (cam) {
  78664. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78665. });
  78666. _this.onApplyObservable.add(function (effect) {
  78667. effect.setColor3("baseColor", _this.color);
  78668. effect.setFloat("depth", _this.depth);
  78669. effect.setFloat("colorLevel", _this.colorLevel);
  78670. effect.setTexture("refractionSampler", _this._refTexture);
  78671. });
  78672. return _this;
  78673. }
  78674. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78675. /**
  78676. * Gets or sets the refraction texture
  78677. * Please note that you are responsible for disposing the texture if you set it manually
  78678. */
  78679. get: function () {
  78680. return this._refTexture;
  78681. },
  78682. set: function (value) {
  78683. if (this._refTexture && this._ownRefractionTexture) {
  78684. this._refTexture.dispose();
  78685. }
  78686. this._refTexture = value;
  78687. this._ownRefractionTexture = false;
  78688. },
  78689. enumerable: true,
  78690. configurable: true
  78691. });
  78692. // Methods
  78693. RefractionPostProcess.prototype.dispose = function (camera) {
  78694. if (this._refTexture && this._ownRefractionTexture) {
  78695. this._refTexture.dispose();
  78696. this._refTexture = null;
  78697. }
  78698. _super.prototype.dispose.call(this, camera);
  78699. };
  78700. return RefractionPostProcess;
  78701. }(BABYLON.PostProcess));
  78702. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78703. })(BABYLON || (BABYLON = {}));
  78704. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78705. var BABYLON;
  78706. (function (BABYLON) {
  78707. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78708. __extends(BlackAndWhitePostProcess, _super);
  78709. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78710. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78711. _this.degree = 1;
  78712. _this.onApplyObservable.add(function (effect) {
  78713. effect.setFloat("degree", _this.degree);
  78714. });
  78715. return _this;
  78716. }
  78717. return BlackAndWhitePostProcess;
  78718. }(BABYLON.PostProcess));
  78719. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78720. })(BABYLON || (BABYLON = {}));
  78721. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78722. var BABYLON;
  78723. (function (BABYLON) {
  78724. /**
  78725. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78726. * input texture to perform effects such as edge detection or sharpening
  78727. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78728. */
  78729. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78730. __extends(ConvolutionPostProcess, _super);
  78731. /**
  78732. * Creates a new instance ConvolutionPostProcess
  78733. * @param name The name of the effect.
  78734. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78735. * @param options The required width/height ratio to downsize to before computing the render pass.
  78736. * @param camera The camera to apply the render pass to.
  78737. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78738. * @param engine The engine which the post process will be applied. (default: current engine)
  78739. * @param reusable If the post process can be reused on the same frame. (default: false)
  78740. * @param textureType Type of textures used when performing the post process. (default: 0)
  78741. */
  78742. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78743. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78744. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78745. _this.kernel = kernel;
  78746. _this.onApply = function (effect) {
  78747. effect.setFloat2("screenSize", _this.width, _this.height);
  78748. effect.setArray("kernel", _this.kernel);
  78749. };
  78750. return _this;
  78751. }
  78752. // Statics
  78753. /**
  78754. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78755. */
  78756. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78757. /**
  78758. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78759. */
  78760. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78761. /**
  78762. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78763. */
  78764. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78765. /**
  78766. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78767. */
  78768. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78769. /**
  78770. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78771. */
  78772. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78773. /**
  78774. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78775. */
  78776. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78777. return ConvolutionPostProcess;
  78778. }(BABYLON.PostProcess));
  78779. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78780. })(BABYLON || (BABYLON = {}));
  78781. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78782. var BABYLON;
  78783. (function (BABYLON) {
  78784. var FilterPostProcess = /** @class */ (function (_super) {
  78785. __extends(FilterPostProcess, _super);
  78786. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78787. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78788. _this.kernelMatrix = kernelMatrix;
  78789. _this.onApply = function (effect) {
  78790. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78791. };
  78792. return _this;
  78793. }
  78794. return FilterPostProcess;
  78795. }(BABYLON.PostProcess));
  78796. BABYLON.FilterPostProcess = FilterPostProcess;
  78797. })(BABYLON || (BABYLON = {}));
  78798. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78799. var BABYLON;
  78800. (function (BABYLON) {
  78801. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78802. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78803. __extends(VolumetricLightScatteringPostProcess, _super);
  78804. /**
  78805. * @constructor
  78806. * @param {string} name - The post-process name
  78807. * @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)
  78808. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78809. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78810. * @param {number} samples - The post-process quality, default 100
  78811. * @param {number} samplingMode - The post-process filtering mode
  78812. * @param {BABYLON.Engine} engine - The babylon engine
  78813. * @param {boolean} reusable - If the post-process is reusable
  78814. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78815. */
  78816. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78817. if (samples === void 0) { samples = 100; }
  78818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78819. 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;
  78820. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78821. /**
  78822. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78823. */
  78824. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78825. /**
  78826. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78827. */
  78828. _this.useCustomMeshPosition = false;
  78829. /**
  78830. * If the post-process should inverse the light scattering direction
  78831. */
  78832. _this.invert = true;
  78833. /**
  78834. * Array containing the excluded meshes not rendered in the internal pass
  78835. */
  78836. _this.excludedMeshes = new Array();
  78837. /**
  78838. * Controls the overall intensity of the post-process
  78839. */
  78840. _this.exposure = 0.3;
  78841. /**
  78842. * Dissipates each sample's contribution in range [0, 1]
  78843. */
  78844. _this.decay = 0.96815;
  78845. /**
  78846. * Controls the overall intensity of each sample
  78847. */
  78848. _this.weight = 0.58767;
  78849. /**
  78850. * Controls the density of each sample
  78851. */
  78852. _this.density = 0.926;
  78853. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78854. engine = scene.getEngine();
  78855. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78856. // Configure mesh
  78857. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78858. // Configure
  78859. _this._createPass(scene, ratio.passRatio || ratio);
  78860. _this.onActivate = function (camera) {
  78861. if (!_this.isSupported) {
  78862. _this.dispose(camera);
  78863. }
  78864. _this.onActivate = null;
  78865. };
  78866. _this.onApplyObservable.add(function (effect) {
  78867. _this._updateMeshScreenCoordinates(scene);
  78868. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78869. effect.setFloat("exposure", _this.exposure);
  78870. effect.setFloat("decay", _this.decay);
  78871. effect.setFloat("weight", _this.weight);
  78872. effect.setFloat("density", _this.density);
  78873. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78874. });
  78875. return _this;
  78876. }
  78877. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78878. get: function () {
  78879. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78880. return false;
  78881. },
  78882. set: function (useDiffuseColor) {
  78883. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78884. },
  78885. enumerable: true,
  78886. configurable: true
  78887. });
  78888. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78889. return "VolumetricLightScatteringPostProcess";
  78890. };
  78891. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78892. var mesh = subMesh.getMesh();
  78893. // Render this.mesh as default
  78894. if (mesh === this.mesh && mesh.material) {
  78895. return mesh.material.isReady(mesh);
  78896. }
  78897. var defines = [];
  78898. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78899. var material = subMesh.getMaterial();
  78900. // Alpha test
  78901. if (material) {
  78902. if (material.needAlphaTesting()) {
  78903. defines.push("#define ALPHATEST");
  78904. }
  78905. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78906. attribs.push(BABYLON.VertexBuffer.UVKind);
  78907. defines.push("#define UV1");
  78908. }
  78909. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78910. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78911. defines.push("#define UV2");
  78912. }
  78913. }
  78914. // Bones
  78915. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78916. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78917. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78918. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78919. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78920. }
  78921. else {
  78922. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78923. }
  78924. // Instances
  78925. if (useInstances) {
  78926. defines.push("#define INSTANCES");
  78927. attribs.push("world0");
  78928. attribs.push("world1");
  78929. attribs.push("world2");
  78930. attribs.push("world3");
  78931. }
  78932. // Get correct effect
  78933. var join = defines.join("\n");
  78934. if (this._cachedDefines !== join) {
  78935. this._cachedDefines = join;
  78936. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78937. }
  78938. return this._volumetricLightScatteringPass.isReady();
  78939. };
  78940. /**
  78941. * Sets the new light position for light scattering effect
  78942. * @param {BABYLON.Vector3} The new custom light position
  78943. */
  78944. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78945. this.customMeshPosition = position;
  78946. };
  78947. /**
  78948. * Returns the light position for light scattering effect
  78949. * @return {BABYLON.Vector3} The custom light position
  78950. */
  78951. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78952. return this.customMeshPosition;
  78953. };
  78954. /**
  78955. * Disposes the internal assets and detaches the post-process from the camera
  78956. */
  78957. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78958. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78959. if (rttIndex !== -1) {
  78960. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78961. }
  78962. this._volumetricLightScatteringRTT.dispose();
  78963. _super.prototype.dispose.call(this, camera);
  78964. };
  78965. /**
  78966. * Returns the render target texture used by the post-process
  78967. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78968. */
  78969. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78970. return this._volumetricLightScatteringRTT;
  78971. };
  78972. // Private methods
  78973. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78974. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78975. return true;
  78976. }
  78977. return false;
  78978. };
  78979. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78980. var _this = this;
  78981. var engine = scene.getEngine();
  78982. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78983. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78984. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78985. this._volumetricLightScatteringRTT.renderList = null;
  78986. this._volumetricLightScatteringRTT.renderParticles = false;
  78987. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78988. var camera = this.getCamera();
  78989. if (camera) {
  78990. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78991. }
  78992. else {
  78993. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78994. }
  78995. // Custom render function for submeshes
  78996. var renderSubMesh = function (subMesh) {
  78997. var mesh = subMesh.getRenderingMesh();
  78998. if (_this._meshExcluded(mesh)) {
  78999. return;
  79000. }
  79001. var material = subMesh.getMaterial();
  79002. if (!material) {
  79003. return;
  79004. }
  79005. var scene = mesh.getScene();
  79006. var engine = scene.getEngine();
  79007. // Culling
  79008. engine.setState(material.backFaceCulling);
  79009. // Managing instances
  79010. var batch = mesh._getInstancesRenderList(subMesh._id);
  79011. if (batch.mustReturn) {
  79012. return;
  79013. }
  79014. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79015. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  79016. var effect = _this._volumetricLightScatteringPass;
  79017. if (mesh === _this.mesh) {
  79018. if (subMesh.effect) {
  79019. effect = subMesh.effect;
  79020. }
  79021. else {
  79022. effect = material.getEffect();
  79023. }
  79024. }
  79025. engine.enableEffect(effect);
  79026. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  79027. if (mesh === _this.mesh) {
  79028. material.bind(mesh.getWorldMatrix(), mesh);
  79029. }
  79030. else {
  79031. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  79032. // Alpha test
  79033. if (material && material.needAlphaTesting()) {
  79034. var alphaTexture = material.getAlphaTestTexture();
  79035. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  79036. if (alphaTexture) {
  79037. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79038. }
  79039. }
  79040. // Bones
  79041. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79042. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79043. }
  79044. }
  79045. // Draw
  79046. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  79047. }
  79048. };
  79049. // Render target texture callbacks
  79050. var savedSceneClearColor;
  79051. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  79052. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  79053. savedSceneClearColor = scene.clearColor;
  79054. scene.clearColor = sceneClearColor;
  79055. });
  79056. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  79057. scene.clearColor = savedSceneClearColor;
  79058. });
  79059. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79060. var engine = scene.getEngine();
  79061. var index;
  79062. if (depthOnlySubMeshes.length) {
  79063. engine.setColorWrite(false);
  79064. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79065. renderSubMesh(depthOnlySubMeshes.data[index]);
  79066. }
  79067. engine.setColorWrite(true);
  79068. }
  79069. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79070. renderSubMesh(opaqueSubMeshes.data[index]);
  79071. }
  79072. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79073. renderSubMesh(alphaTestSubMeshes.data[index]);
  79074. }
  79075. if (transparentSubMeshes.length) {
  79076. // Sort sub meshes
  79077. for (index = 0; index < transparentSubMeshes.length; index++) {
  79078. var submesh = transparentSubMeshes.data[index];
  79079. var boundingInfo = submesh.getBoundingInfo();
  79080. if (boundingInfo && scene.activeCamera) {
  79081. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  79082. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  79083. }
  79084. }
  79085. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  79086. sortedArray.sort(function (a, b) {
  79087. // Alpha index first
  79088. if (a._alphaIndex > b._alphaIndex) {
  79089. return 1;
  79090. }
  79091. if (a._alphaIndex < b._alphaIndex) {
  79092. return -1;
  79093. }
  79094. // Then distance to camera
  79095. if (a._distanceToCamera < b._distanceToCamera) {
  79096. return 1;
  79097. }
  79098. if (a._distanceToCamera > b._distanceToCamera) {
  79099. return -1;
  79100. }
  79101. return 0;
  79102. });
  79103. // Render sub meshes
  79104. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  79105. for (index = 0; index < sortedArray.length; index++) {
  79106. renderSubMesh(sortedArray[index]);
  79107. }
  79108. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79109. }
  79110. };
  79111. };
  79112. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  79113. var transform = scene.getTransformMatrix();
  79114. var meshPosition;
  79115. if (this.useCustomMeshPosition) {
  79116. meshPosition = this.customMeshPosition;
  79117. }
  79118. else if (this.attachedNode) {
  79119. meshPosition = this.attachedNode.position;
  79120. }
  79121. else {
  79122. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  79123. }
  79124. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  79125. this._screenCoordinates.x = pos.x / this._viewPort.width;
  79126. this._screenCoordinates.y = pos.y / this._viewPort.height;
  79127. if (this.invert)
  79128. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  79129. };
  79130. // Static methods
  79131. /**
  79132. * Creates a default mesh for the Volumeric Light Scattering post-process
  79133. * @param {string} The mesh name
  79134. * @param {BABYLON.Scene} The scene where to create the mesh
  79135. * @return {BABYLON.Mesh} the default mesh
  79136. */
  79137. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  79138. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  79139. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  79140. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  79141. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  79142. mesh.material = material;
  79143. return mesh;
  79144. };
  79145. __decorate([
  79146. BABYLON.serializeAsVector3()
  79147. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  79148. __decorate([
  79149. BABYLON.serialize()
  79150. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  79151. __decorate([
  79152. BABYLON.serialize()
  79153. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  79154. __decorate([
  79155. BABYLON.serializeAsMeshReference()
  79156. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  79157. __decorate([
  79158. BABYLON.serialize()
  79159. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  79160. __decorate([
  79161. BABYLON.serialize()
  79162. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  79163. __decorate([
  79164. BABYLON.serialize()
  79165. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  79166. __decorate([
  79167. BABYLON.serialize()
  79168. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  79169. __decorate([
  79170. BABYLON.serialize()
  79171. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  79172. return VolumetricLightScatteringPostProcess;
  79173. }(BABYLON.PostProcess));
  79174. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  79175. })(BABYLON || (BABYLON = {}));
  79176. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  79177. //
  79178. // This post-process allows the modification of rendered colors by using
  79179. // a 'look-up table' (LUT). This effect is also called Color Grading.
  79180. //
  79181. // The object needs to be provided an url to a texture containing the color
  79182. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  79183. // Use an image editing software to tweak the LUT to match your needs.
  79184. //
  79185. // For an example of a color LUT, see here:
  79186. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  79187. // For explanations on color grading, see here:
  79188. // http://udn.epicgames.com/Three/ColorGrading.html
  79189. //
  79190. var BABYLON;
  79191. (function (BABYLON) {
  79192. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  79193. __extends(ColorCorrectionPostProcess, _super);
  79194. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  79195. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  79196. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79197. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  79198. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79199. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79200. _this.onApply = function (effect) {
  79201. effect.setTexture("colorTable", _this._colorTableTexture);
  79202. };
  79203. return _this;
  79204. }
  79205. return ColorCorrectionPostProcess;
  79206. }(BABYLON.PostProcess));
  79207. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  79208. })(BABYLON || (BABYLON = {}));
  79209. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  79210. var BABYLON;
  79211. (function (BABYLON) {
  79212. /** Defines operator used for tonemapping */
  79213. var TonemappingOperator;
  79214. (function (TonemappingOperator) {
  79215. /** Hable */
  79216. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  79217. /** Reinhard */
  79218. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  79219. /** HejiDawson */
  79220. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  79221. /** Photographic */
  79222. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  79223. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  79224. ;
  79225. /**
  79226. * Defines a post process to apply tone mapping
  79227. */
  79228. var TonemapPostProcess = /** @class */ (function (_super) {
  79229. __extends(TonemapPostProcess, _super);
  79230. /**
  79231. * Creates a new TonemapPostProcess
  79232. * @param name defines the name of the postprocess
  79233. * @param _operator defines the operator to use
  79234. * @param exposureAdjustment defines the required exposure adjustement
  79235. * @param camera defines the camera to use (can be null)
  79236. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  79237. * @param engine defines the hosting engine (can be ignore if camera is set)
  79238. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  79239. */
  79240. function TonemapPostProcess(name, _operator,
  79241. /** Defines the required exposure adjustement */
  79242. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79243. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79244. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79245. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79246. _this._operator = _operator;
  79247. _this.exposureAdjustment = exposureAdjustment;
  79248. var defines = "#define ";
  79249. if (_this._operator === TonemappingOperator.Hable)
  79250. defines += "HABLE_TONEMAPPING";
  79251. else if (_this._operator === TonemappingOperator.Reinhard)
  79252. defines += "REINHARD_TONEMAPPING";
  79253. else if (_this._operator === TonemappingOperator.HejiDawson)
  79254. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79255. else if (_this._operator === TonemappingOperator.Photographic)
  79256. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79257. //sadly a second call to create the effect.
  79258. _this.updateEffect(defines);
  79259. _this.onApply = function (effect) {
  79260. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79261. };
  79262. return _this;
  79263. }
  79264. return TonemapPostProcess;
  79265. }(BABYLON.PostProcess));
  79266. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79267. })(BABYLON || (BABYLON = {}));
  79268. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79269. var BABYLON;
  79270. (function (BABYLON) {
  79271. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79272. __extends(DisplayPassPostProcess, _super);
  79273. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79274. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79275. }
  79276. return DisplayPassPostProcess;
  79277. }(BABYLON.PostProcess));
  79278. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79279. })(BABYLON || (BABYLON = {}));
  79280. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79281. var BABYLON;
  79282. (function (BABYLON) {
  79283. var HighlightsPostProcess = /** @class */ (function (_super) {
  79284. __extends(HighlightsPostProcess, _super);
  79285. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79286. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79287. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79288. }
  79289. return HighlightsPostProcess;
  79290. }(BABYLON.PostProcess));
  79291. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79292. })(BABYLON || (BABYLON = {}));
  79293. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79294. var BABYLON;
  79295. (function (BABYLON) {
  79296. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79297. __extends(ImageProcessingPostProcess, _super);
  79298. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79299. if (camera === void 0) { camera = null; }
  79300. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79301. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79302. _this._fromLinearSpace = true;
  79303. /**
  79304. * Defines cache preventing GC.
  79305. */
  79306. _this._defines = {
  79307. IMAGEPROCESSING: false,
  79308. VIGNETTE: false,
  79309. VIGNETTEBLENDMODEMULTIPLY: false,
  79310. VIGNETTEBLENDMODEOPAQUE: false,
  79311. TONEMAPPING: false,
  79312. CONTRAST: false,
  79313. COLORCURVES: false,
  79314. COLORGRADING: false,
  79315. COLORGRADING3D: false,
  79316. FROMLINEARSPACE: false,
  79317. SAMPLER3DGREENDEPTH: false,
  79318. SAMPLER3DBGRMAP: false,
  79319. IMAGEPROCESSINGPOSTPROCESS: false,
  79320. EXPOSURE: false,
  79321. };
  79322. // Setup the configuration as forced by the constructor. This would then not force the
  79323. // scene materials output in linear space and let untouched the default forward pass.
  79324. if (imageProcessingConfiguration) {
  79325. imageProcessingConfiguration.applyByPostProcess = true;
  79326. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79327. // This will cause the shader to be compiled
  79328. _this.fromLinearSpace = false;
  79329. }
  79330. // Setup the default processing configuration to the scene.
  79331. else {
  79332. _this._attachImageProcessingConfiguration(null, true);
  79333. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79334. }
  79335. _this.onApply = function (effect) {
  79336. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79337. };
  79338. return _this;
  79339. }
  79340. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79341. /**
  79342. * Gets the image processing configuration used either in this material.
  79343. */
  79344. get: function () {
  79345. return this._imageProcessingConfiguration;
  79346. },
  79347. /**
  79348. * Sets the Default image processing configuration used either in the this material.
  79349. *
  79350. * If sets to null, the scene one is in use.
  79351. */
  79352. set: function (value) {
  79353. this._attachImageProcessingConfiguration(value);
  79354. },
  79355. enumerable: true,
  79356. configurable: true
  79357. });
  79358. /**
  79359. * Attaches a new image processing configuration to the PBR Material.
  79360. * @param configuration
  79361. */
  79362. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79363. var _this = this;
  79364. if (doNotBuild === void 0) { doNotBuild = false; }
  79365. if (configuration === this._imageProcessingConfiguration) {
  79366. return;
  79367. }
  79368. // Detaches observer.
  79369. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79370. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79371. }
  79372. // Pick the scene configuration if needed.
  79373. if (!configuration) {
  79374. var scene = null;
  79375. var engine = this.getEngine();
  79376. var camera = this.getCamera();
  79377. if (camera) {
  79378. scene = camera.getScene();
  79379. }
  79380. else if (engine && engine.scenes) {
  79381. var scenes = engine.scenes;
  79382. scene = scenes[scenes.length - 1];
  79383. }
  79384. else {
  79385. scene = BABYLON.Engine.LastCreatedScene;
  79386. }
  79387. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79388. }
  79389. else {
  79390. this._imageProcessingConfiguration = configuration;
  79391. }
  79392. // Attaches observer.
  79393. if (this._imageProcessingConfiguration) {
  79394. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79395. _this._updateParameters();
  79396. });
  79397. }
  79398. // Ensure the effect will be rebuilt.
  79399. if (!doNotBuild) {
  79400. this._updateParameters();
  79401. }
  79402. };
  79403. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79404. /**
  79405. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79406. */
  79407. get: function () {
  79408. return this.imageProcessingConfiguration.colorCurves;
  79409. },
  79410. /**
  79411. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79412. */
  79413. set: function (value) {
  79414. this.imageProcessingConfiguration.colorCurves = value;
  79415. },
  79416. enumerable: true,
  79417. configurable: true
  79418. });
  79419. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79420. /**
  79421. * Gets wether the color curves effect is enabled.
  79422. */
  79423. get: function () {
  79424. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79425. },
  79426. /**
  79427. * Sets wether the color curves effect is enabled.
  79428. */
  79429. set: function (value) {
  79430. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79431. },
  79432. enumerable: true,
  79433. configurable: true
  79434. });
  79435. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79436. /**
  79437. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79438. */
  79439. get: function () {
  79440. return this.imageProcessingConfiguration.colorGradingTexture;
  79441. },
  79442. /**
  79443. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79444. */
  79445. set: function (value) {
  79446. this.imageProcessingConfiguration.colorGradingTexture = value;
  79447. },
  79448. enumerable: true,
  79449. configurable: true
  79450. });
  79451. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79452. /**
  79453. * Gets wether the color grading effect is enabled.
  79454. */
  79455. get: function () {
  79456. return this.imageProcessingConfiguration.colorGradingEnabled;
  79457. },
  79458. /**
  79459. * Gets wether the color grading effect is enabled.
  79460. */
  79461. set: function (value) {
  79462. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79463. },
  79464. enumerable: true,
  79465. configurable: true
  79466. });
  79467. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79468. /**
  79469. * Gets exposure used in the effect.
  79470. */
  79471. get: function () {
  79472. return this.imageProcessingConfiguration.exposure;
  79473. },
  79474. /**
  79475. * Sets exposure used in the effect.
  79476. */
  79477. set: function (value) {
  79478. this.imageProcessingConfiguration.exposure = value;
  79479. },
  79480. enumerable: true,
  79481. configurable: true
  79482. });
  79483. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79484. /**
  79485. * Gets wether tonemapping is enabled or not.
  79486. */
  79487. get: function () {
  79488. return this._imageProcessingConfiguration.toneMappingEnabled;
  79489. },
  79490. /**
  79491. * Sets wether tonemapping is enabled or not
  79492. */
  79493. set: function (value) {
  79494. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79495. },
  79496. enumerable: true,
  79497. configurable: true
  79498. });
  79499. ;
  79500. ;
  79501. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79502. /**
  79503. * Gets contrast used in the effect.
  79504. */
  79505. get: function () {
  79506. return this.imageProcessingConfiguration.contrast;
  79507. },
  79508. /**
  79509. * Sets contrast used in the effect.
  79510. */
  79511. set: function (value) {
  79512. this.imageProcessingConfiguration.contrast = value;
  79513. },
  79514. enumerable: true,
  79515. configurable: true
  79516. });
  79517. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79518. /**
  79519. * Gets Vignette stretch size.
  79520. */
  79521. get: function () {
  79522. return this.imageProcessingConfiguration.vignetteStretch;
  79523. },
  79524. /**
  79525. * Sets Vignette stretch size.
  79526. */
  79527. set: function (value) {
  79528. this.imageProcessingConfiguration.vignetteStretch = value;
  79529. },
  79530. enumerable: true,
  79531. configurable: true
  79532. });
  79533. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79534. /**
  79535. * Gets Vignette centre X Offset.
  79536. */
  79537. get: function () {
  79538. return this.imageProcessingConfiguration.vignetteCentreX;
  79539. },
  79540. /**
  79541. * Sets Vignette centre X Offset.
  79542. */
  79543. set: function (value) {
  79544. this.imageProcessingConfiguration.vignetteCentreX = value;
  79545. },
  79546. enumerable: true,
  79547. configurable: true
  79548. });
  79549. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79550. /**
  79551. * Gets Vignette centre Y Offset.
  79552. */
  79553. get: function () {
  79554. return this.imageProcessingConfiguration.vignetteCentreY;
  79555. },
  79556. /**
  79557. * Sets Vignette centre Y Offset.
  79558. */
  79559. set: function (value) {
  79560. this.imageProcessingConfiguration.vignetteCentreY = value;
  79561. },
  79562. enumerable: true,
  79563. configurable: true
  79564. });
  79565. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79566. /**
  79567. * Gets Vignette weight or intensity of the vignette effect.
  79568. */
  79569. get: function () {
  79570. return this.imageProcessingConfiguration.vignetteWeight;
  79571. },
  79572. /**
  79573. * Sets Vignette weight or intensity of the vignette effect.
  79574. */
  79575. set: function (value) {
  79576. this.imageProcessingConfiguration.vignetteWeight = value;
  79577. },
  79578. enumerable: true,
  79579. configurable: true
  79580. });
  79581. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79582. /**
  79583. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79584. * if vignetteEnabled is set to true.
  79585. */
  79586. get: function () {
  79587. return this.imageProcessingConfiguration.vignetteColor;
  79588. },
  79589. /**
  79590. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79591. * if vignetteEnabled is set to true.
  79592. */
  79593. set: function (value) {
  79594. this.imageProcessingConfiguration.vignetteColor = value;
  79595. },
  79596. enumerable: true,
  79597. configurable: true
  79598. });
  79599. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79600. /**
  79601. * Gets Camera field of view used by the Vignette effect.
  79602. */
  79603. get: function () {
  79604. return this.imageProcessingConfiguration.vignetteCameraFov;
  79605. },
  79606. /**
  79607. * Sets Camera field of view used by the Vignette effect.
  79608. */
  79609. set: function (value) {
  79610. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79611. },
  79612. enumerable: true,
  79613. configurable: true
  79614. });
  79615. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79616. /**
  79617. * Gets the vignette blend mode allowing different kind of effect.
  79618. */
  79619. get: function () {
  79620. return this.imageProcessingConfiguration.vignetteBlendMode;
  79621. },
  79622. /**
  79623. * Sets the vignette blend mode allowing different kind of effect.
  79624. */
  79625. set: function (value) {
  79626. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79627. },
  79628. enumerable: true,
  79629. configurable: true
  79630. });
  79631. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79632. /**
  79633. * Gets wether the vignette effect is enabled.
  79634. */
  79635. get: function () {
  79636. return this.imageProcessingConfiguration.vignetteEnabled;
  79637. },
  79638. /**
  79639. * Sets wether the vignette effect is enabled.
  79640. */
  79641. set: function (value) {
  79642. this.imageProcessingConfiguration.vignetteEnabled = value;
  79643. },
  79644. enumerable: true,
  79645. configurable: true
  79646. });
  79647. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79648. /**
  79649. * Gets wether the input of the processing is in Gamma or Linear Space.
  79650. */
  79651. get: function () {
  79652. return this._fromLinearSpace;
  79653. },
  79654. /**
  79655. * Sets wether the input of the processing is in Gamma or Linear Space.
  79656. */
  79657. set: function (value) {
  79658. if (this._fromLinearSpace === value) {
  79659. return;
  79660. }
  79661. this._fromLinearSpace = value;
  79662. this._updateParameters();
  79663. },
  79664. enumerable: true,
  79665. configurable: true
  79666. });
  79667. ImageProcessingPostProcess.prototype.getClassName = function () {
  79668. return "ImageProcessingPostProcess";
  79669. };
  79670. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79671. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79672. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79673. var defines = "";
  79674. for (var define in this._defines) {
  79675. if (this._defines[define]) {
  79676. defines += "#define " + define + ";\r\n";
  79677. }
  79678. }
  79679. var samplers = ["textureSampler"];
  79680. var uniforms = ["scale"];
  79681. if (BABYLON.ImageProcessingConfiguration) {
  79682. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79683. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79684. }
  79685. this.updateEffect(defines, uniforms, samplers);
  79686. };
  79687. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79688. _super.prototype.dispose.call(this, camera);
  79689. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79690. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79691. }
  79692. if (this._imageProcessingConfiguration) {
  79693. this.imageProcessingConfiguration.applyByPostProcess = false;
  79694. }
  79695. };
  79696. __decorate([
  79697. BABYLON.serialize()
  79698. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79699. return ImageProcessingPostProcess;
  79700. }(BABYLON.PostProcess));
  79701. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79702. })(BABYLON || (BABYLON = {}));
  79703. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79704. var BABYLON;
  79705. (function (BABYLON) {
  79706. /**
  79707. * Class used to store bone information
  79708. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79709. */
  79710. var Bone = /** @class */ (function (_super) {
  79711. __extends(Bone, _super);
  79712. /**
  79713. * Create a new bone
  79714. * @param name defines the bone name
  79715. * @param skeleton defines the parent skeleton
  79716. * @param parentBone defines the parent (can be null if the bone is the root)
  79717. * @param localMatrix defines the local matrix
  79718. * @param restPose defines the rest pose matrix
  79719. * @param baseMatrix defines the base matrix
  79720. * @param index defines index of the bone in the hiearchy
  79721. */
  79722. function Bone(
  79723. /**
  79724. * defines the bone name
  79725. */
  79726. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79727. if (parentBone === void 0) { parentBone = null; }
  79728. if (localMatrix === void 0) { localMatrix = null; }
  79729. if (restPose === void 0) { restPose = null; }
  79730. if (baseMatrix === void 0) { baseMatrix = null; }
  79731. if (index === void 0) { index = null; }
  79732. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79733. _this.name = name;
  79734. /**
  79735. * Gets the list of child bones
  79736. */
  79737. _this.children = new Array();
  79738. /** Gets the animations associated with this bone */
  79739. _this.animations = new Array();
  79740. /**
  79741. * @hidden Internal only
  79742. * Set this value to map this bone to a different index in the transform matrices
  79743. * Set this value to -1 to exclude the bone from the transform matrices
  79744. */
  79745. _this._index = null;
  79746. _this._absoluteTransform = new BABYLON.Matrix();
  79747. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79748. _this._scalingDeterminant = 1;
  79749. _this._worldTransform = new BABYLON.Matrix();
  79750. _this._needToDecompose = true;
  79751. _this._needToCompose = false;
  79752. _this._skeleton = skeleton;
  79753. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79754. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79755. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79756. _this._index = index;
  79757. skeleton.bones.push(_this);
  79758. _this.setParent(parentBone, false);
  79759. if (baseMatrix || localMatrix) {
  79760. _this._updateDifferenceMatrix();
  79761. }
  79762. return _this;
  79763. }
  79764. Object.defineProperty(Bone.prototype, "_matrix", {
  79765. /** @hidden */
  79766. get: function () {
  79767. this._compose();
  79768. return this._localMatrix;
  79769. },
  79770. /** @hidden */
  79771. set: function (value) {
  79772. this._localMatrix.copyFrom(value);
  79773. this._needToDecompose = true;
  79774. },
  79775. enumerable: true,
  79776. configurable: true
  79777. });
  79778. // Members
  79779. /**
  79780. * Gets the parent skeleton
  79781. * @returns a skeleton
  79782. */
  79783. Bone.prototype.getSkeleton = function () {
  79784. return this._skeleton;
  79785. };
  79786. /**
  79787. * Gets parent bone
  79788. * @returns a bone or null if the bone is the root of the bone hierarchy
  79789. */
  79790. Bone.prototype.getParent = function () {
  79791. return this._parent;
  79792. };
  79793. /**
  79794. * Sets the parent bone
  79795. * @param parent defines the parent (can be null if the bone is the root)
  79796. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79797. */
  79798. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79799. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79800. if (this._parent === parent) {
  79801. return;
  79802. }
  79803. if (this._parent) {
  79804. var index = this._parent.children.indexOf(this);
  79805. if (index !== -1) {
  79806. this._parent.children.splice(index, 1);
  79807. }
  79808. }
  79809. this._parent = parent;
  79810. if (this._parent) {
  79811. this._parent.children.push(this);
  79812. }
  79813. if (updateDifferenceMatrix) {
  79814. this._updateDifferenceMatrix();
  79815. }
  79816. this.markAsDirty();
  79817. };
  79818. /**
  79819. * Gets the local matrix
  79820. * @returns a matrix
  79821. */
  79822. Bone.prototype.getLocalMatrix = function () {
  79823. this._compose();
  79824. return this._localMatrix;
  79825. };
  79826. /**
  79827. * Gets the base matrix (initial matrix which remains unchanged)
  79828. * @returns a matrix
  79829. */
  79830. Bone.prototype.getBaseMatrix = function () {
  79831. return this._baseMatrix;
  79832. };
  79833. /**
  79834. * Gets the rest pose matrix
  79835. * @returns a matrix
  79836. */
  79837. Bone.prototype.getRestPose = function () {
  79838. return this._restPose;
  79839. };
  79840. /**
  79841. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79842. */
  79843. Bone.prototype.getWorldMatrix = function () {
  79844. return this._worldTransform;
  79845. };
  79846. /**
  79847. * Sets the local matrix to rest pose matrix
  79848. */
  79849. Bone.prototype.returnToRest = function () {
  79850. this.updateMatrix(this._restPose.clone());
  79851. };
  79852. /**
  79853. * Gets the inverse of the absolute transform matrix.
  79854. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79855. * @returns a matrix
  79856. */
  79857. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79858. return this._invertedAbsoluteTransform;
  79859. };
  79860. /**
  79861. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79862. * @returns a matrix
  79863. */
  79864. Bone.prototype.getAbsoluteTransform = function () {
  79865. return this._absoluteTransform;
  79866. };
  79867. Object.defineProperty(Bone.prototype, "position", {
  79868. // Properties (matches AbstractMesh properties)
  79869. /** Gets or sets current position (in local space) */
  79870. get: function () {
  79871. this._decompose();
  79872. return this._localPosition;
  79873. },
  79874. set: function (newPosition) {
  79875. this._decompose();
  79876. this._localPosition.copyFrom(newPosition);
  79877. this._markAsDirtyAndCompose();
  79878. },
  79879. enumerable: true,
  79880. configurable: true
  79881. });
  79882. Object.defineProperty(Bone.prototype, "rotation", {
  79883. /** Gets or sets current rotation (in local space) */
  79884. get: function () {
  79885. return this.getRotation();
  79886. },
  79887. set: function (newRotation) {
  79888. this.setRotation(newRotation);
  79889. },
  79890. enumerable: true,
  79891. configurable: true
  79892. });
  79893. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79894. /** Gets or sets current rotation quaternion (in local space) */
  79895. get: function () {
  79896. this._decompose();
  79897. return this._localRotation;
  79898. },
  79899. set: function (newRotation) {
  79900. this.setRotationQuaternion(newRotation);
  79901. },
  79902. enumerable: true,
  79903. configurable: true
  79904. });
  79905. Object.defineProperty(Bone.prototype, "scaling", {
  79906. /** Gets or sets current scaling (in local space) */
  79907. get: function () {
  79908. return this.getScale();
  79909. },
  79910. set: function (newScaling) {
  79911. this.setScale(newScaling);
  79912. },
  79913. enumerable: true,
  79914. configurable: true
  79915. });
  79916. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79917. /**
  79918. * Gets the animation properties override
  79919. */
  79920. get: function () {
  79921. return this._skeleton.animationPropertiesOverride;
  79922. },
  79923. enumerable: true,
  79924. configurable: true
  79925. });
  79926. // Methods
  79927. Bone.prototype._decompose = function () {
  79928. if (!this._needToDecompose) {
  79929. return;
  79930. }
  79931. this._needToDecompose = false;
  79932. if (!this._localScaling) {
  79933. this._localScaling = BABYLON.Vector3.Zero();
  79934. this._localRotation = BABYLON.Quaternion.Zero();
  79935. this._localPosition = BABYLON.Vector3.Zero();
  79936. }
  79937. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79938. };
  79939. Bone.prototype._compose = function () {
  79940. if (!this._needToCompose) {
  79941. return;
  79942. }
  79943. this._needToCompose = false;
  79944. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79945. };
  79946. /**
  79947. * Update the base and local matrices
  79948. * @param matrix defines the new base or local matrix
  79949. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79950. * @param updateLocalMatrix defines if the local matrix should be updated
  79951. */
  79952. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79953. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79954. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79955. this._baseMatrix.copyFrom(matrix);
  79956. if (updateDifferenceMatrix) {
  79957. this._updateDifferenceMatrix();
  79958. }
  79959. if (updateLocalMatrix) {
  79960. this._localMatrix.copyFrom(matrix);
  79961. this._markAsDirtyAndDecompose();
  79962. }
  79963. else {
  79964. this.markAsDirty();
  79965. }
  79966. };
  79967. /** @hidden */
  79968. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79969. if (updateChildren === void 0) { updateChildren = true; }
  79970. if (!rootMatrix) {
  79971. rootMatrix = this._baseMatrix;
  79972. }
  79973. if (this._parent) {
  79974. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79975. }
  79976. else {
  79977. this._absoluteTransform.copyFrom(rootMatrix);
  79978. }
  79979. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79980. if (updateChildren) {
  79981. for (var index = 0; index < this.children.length; index++) {
  79982. this.children[index]._updateDifferenceMatrix();
  79983. }
  79984. }
  79985. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79986. };
  79987. /**
  79988. * Flag the bone as dirty (Forcing it to update everything)
  79989. */
  79990. Bone.prototype.markAsDirty = function () {
  79991. this._currentRenderId++;
  79992. this._childRenderId++;
  79993. this._skeleton._markAsDirty();
  79994. };
  79995. Bone.prototype._markAsDirtyAndCompose = function () {
  79996. this.markAsDirty();
  79997. this._needToCompose = true;
  79998. };
  79999. Bone.prototype._markAsDirtyAndDecompose = function () {
  80000. this.markAsDirty();
  80001. this._needToDecompose = true;
  80002. };
  80003. /**
  80004. * Copy an animation range from another bone
  80005. * @param source defines the source bone
  80006. * @param rangeName defines the range name to copy
  80007. * @param frameOffset defines the frame offset
  80008. * @param rescaleAsRequired defines if rescaling must be applied if required
  80009. * @param skelDimensionsRatio defines the scaling ratio
  80010. * @returns true if operation was successful
  80011. */
  80012. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  80013. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80014. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  80015. // all animation may be coming from a library skeleton, so may need to create animation
  80016. if (this.animations.length === 0) {
  80017. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  80018. this.animations[0].setKeys([]);
  80019. }
  80020. // get animation info / verify there is such a range from the source bone
  80021. var sourceRange = source.animations[0].getRange(rangeName);
  80022. if (!sourceRange) {
  80023. return false;
  80024. }
  80025. var from = sourceRange.from;
  80026. var to = sourceRange.to;
  80027. var sourceKeys = source.animations[0].getKeys();
  80028. // rescaling prep
  80029. var sourceBoneLength = source.length;
  80030. var sourceParent = source.getParent();
  80031. var parent = this.getParent();
  80032. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  80033. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  80034. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  80035. var destKeys = this.animations[0].getKeys();
  80036. // loop vars declaration
  80037. var orig;
  80038. var origTranslation;
  80039. var mat;
  80040. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  80041. orig = sourceKeys[key];
  80042. if (orig.frame >= from && orig.frame <= to) {
  80043. if (rescaleAsRequired) {
  80044. mat = orig.value.clone();
  80045. // scale based on parent ratio, when bone has parent
  80046. if (parentScalingReqd) {
  80047. origTranslation = mat.getTranslation();
  80048. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  80049. // scale based on skeleton dimension ratio when root bone, and value is passed
  80050. }
  80051. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  80052. origTranslation = mat.getTranslation();
  80053. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  80054. // use original when root bone, and no data for skelDimensionsRatio
  80055. }
  80056. else {
  80057. mat = orig.value;
  80058. }
  80059. }
  80060. else {
  80061. mat = orig.value;
  80062. }
  80063. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  80064. }
  80065. }
  80066. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  80067. return true;
  80068. };
  80069. /**
  80070. * Translate the bone in local or world space
  80071. * @param vec The amount to translate the bone
  80072. * @param space The space that the translation is in
  80073. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80074. */
  80075. Bone.prototype.translate = function (vec, space, mesh) {
  80076. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80077. var lm = this.getLocalMatrix();
  80078. if (space == BABYLON.Space.LOCAL) {
  80079. lm.m[12] += vec.x;
  80080. lm.m[13] += vec.y;
  80081. lm.m[14] += vec.z;
  80082. }
  80083. else {
  80084. var wm = null;
  80085. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80086. if (mesh) {
  80087. wm = mesh.getWorldMatrix();
  80088. }
  80089. this._skeleton.computeAbsoluteTransforms();
  80090. var tmat = Bone._tmpMats[0];
  80091. var tvec = Bone._tmpVecs[0];
  80092. if (this._parent) {
  80093. if (mesh && wm) {
  80094. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80095. tmat.multiplyToRef(wm, tmat);
  80096. }
  80097. else {
  80098. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80099. }
  80100. }
  80101. tmat.m[12] = 0;
  80102. tmat.m[13] = 0;
  80103. tmat.m[14] = 0;
  80104. tmat.invert();
  80105. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  80106. lm.m[12] += tvec.x;
  80107. lm.m[13] += tvec.y;
  80108. lm.m[14] += tvec.z;
  80109. }
  80110. this._markAsDirtyAndDecompose();
  80111. };
  80112. /**
  80113. * Set the postion of the bone in local or world space
  80114. * @param position The position to set the bone
  80115. * @param space The space that the position is in
  80116. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80117. */
  80118. Bone.prototype.setPosition = function (position, space, mesh) {
  80119. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80120. var lm = this.getLocalMatrix();
  80121. if (space == BABYLON.Space.LOCAL) {
  80122. lm.m[12] = position.x;
  80123. lm.m[13] = position.y;
  80124. lm.m[14] = position.z;
  80125. }
  80126. else {
  80127. var wm = null;
  80128. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80129. if (mesh) {
  80130. wm = mesh.getWorldMatrix();
  80131. }
  80132. this._skeleton.computeAbsoluteTransforms();
  80133. var tmat = Bone._tmpMats[0];
  80134. var vec = Bone._tmpVecs[0];
  80135. if (this._parent) {
  80136. if (mesh && wm) {
  80137. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80138. tmat.multiplyToRef(wm, tmat);
  80139. }
  80140. else {
  80141. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80142. }
  80143. }
  80144. tmat.invert();
  80145. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  80146. lm.m[12] = vec.x;
  80147. lm.m[13] = vec.y;
  80148. lm.m[14] = vec.z;
  80149. }
  80150. this._markAsDirtyAndDecompose();
  80151. };
  80152. /**
  80153. * Set the absolute position of the bone (world space)
  80154. * @param position The position to set the bone
  80155. * @param mesh The mesh that this bone is attached to
  80156. */
  80157. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  80158. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  80159. };
  80160. /**
  80161. * Scale the bone on the x, y and z axes (in local space)
  80162. * @param x The amount to scale the bone on the x axis
  80163. * @param y The amount to scale the bone on the y axis
  80164. * @param z The amount to scale the bone on the z axis
  80165. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  80166. */
  80167. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  80168. if (scaleChildren === void 0) { scaleChildren = false; }
  80169. var locMat = this.getLocalMatrix();
  80170. // Apply new scaling on top of current local matrix
  80171. var scaleMat = Bone._tmpMats[0];
  80172. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  80173. scaleMat.multiplyToRef(locMat, locMat);
  80174. // Invert scaling matrix and apply the inverse to all children
  80175. scaleMat.invert();
  80176. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  80177. var child = _a[_i];
  80178. var cm = child.getLocalMatrix();
  80179. cm.multiplyToRef(scaleMat, cm);
  80180. cm.m[12] *= x;
  80181. cm.m[13] *= y;
  80182. cm.m[14] *= z;
  80183. child._markAsDirtyAndDecompose();
  80184. }
  80185. this._markAsDirtyAndDecompose();
  80186. if (scaleChildren) {
  80187. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  80188. var child = _c[_b];
  80189. child.scale(x, y, z, scaleChildren);
  80190. }
  80191. }
  80192. };
  80193. /**
  80194. * Set the bone scaling in local space
  80195. * @param scale defines the scaling vector
  80196. */
  80197. Bone.prototype.setScale = function (scale) {
  80198. this._decompose();
  80199. this._localScaling.copyFrom(scale);
  80200. this._markAsDirtyAndCompose();
  80201. };
  80202. /**
  80203. * Gets the current scaling in local space
  80204. * @returns the current scaling vector
  80205. */
  80206. Bone.prototype.getScale = function () {
  80207. this._decompose();
  80208. return this._localScaling;
  80209. };
  80210. /**
  80211. * Gets the current scaling in local space and stores it in a target vector
  80212. * @param result defines the target vector
  80213. */
  80214. Bone.prototype.getScaleToRef = function (result) {
  80215. this._decompose();
  80216. result.copyFrom(this._localScaling);
  80217. };
  80218. /**
  80219. * Set the yaw, pitch, and roll of the bone in local or world space
  80220. * @param yaw The rotation of the bone on the y axis
  80221. * @param pitch The rotation of the bone on the x axis
  80222. * @param roll The rotation of the bone on the z axis
  80223. * @param space The space that the axes of rotation are in
  80224. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80225. */
  80226. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  80227. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80228. if (space === BABYLON.Space.LOCAL) {
  80229. var quat = Bone._tmpQuat;
  80230. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  80231. this.setRotationQuaternion(quat, space, mesh);
  80232. return;
  80233. }
  80234. var rotMatInv = Bone._tmpMats[0];
  80235. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80236. return;
  80237. }
  80238. var rotMat = Bone._tmpMats[1];
  80239. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  80240. rotMatInv.multiplyToRef(rotMat, rotMat);
  80241. this._rotateWithMatrix(rotMat, space, mesh);
  80242. };
  80243. /**
  80244. * Add a rotation to the bone on an axis in local or world space
  80245. * @param axis The axis to rotate the bone on
  80246. * @param amount The amount to rotate the bone
  80247. * @param space The space that the axis is in
  80248. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80249. */
  80250. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80251. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80252. var rmat = Bone._tmpMats[0];
  80253. rmat.m[12] = 0;
  80254. rmat.m[13] = 0;
  80255. rmat.m[14] = 0;
  80256. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80257. this._rotateWithMatrix(rmat, space, mesh);
  80258. };
  80259. /**
  80260. * Set the rotation of the bone to a particular axis angle in local or world space
  80261. * @param axis The axis to rotate the bone on
  80262. * @param angle The angle that the bone should be rotated to
  80263. * @param space The space that the axis is in
  80264. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80265. */
  80266. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80267. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80268. if (space === BABYLON.Space.LOCAL) {
  80269. var quat = Bone._tmpQuat;
  80270. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80271. this.setRotationQuaternion(quat, space, mesh);
  80272. return;
  80273. }
  80274. var rotMatInv = Bone._tmpMats[0];
  80275. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80276. return;
  80277. }
  80278. var rotMat = Bone._tmpMats[1];
  80279. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80280. rotMatInv.multiplyToRef(rotMat, rotMat);
  80281. this._rotateWithMatrix(rotMat, space, mesh);
  80282. };
  80283. /**
  80284. * Set the euler rotation of the bone in local of world space
  80285. * @param rotation The euler rotation that the bone should be set to
  80286. * @param space The space that the rotation is in
  80287. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80288. */
  80289. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80290. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80291. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80292. };
  80293. /**
  80294. * Set the quaternion rotation of the bone in local of world space
  80295. * @param quat The quaternion rotation that the bone should be set to
  80296. * @param space The space that the rotation is in
  80297. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80298. */
  80299. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80300. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80301. if (space === BABYLON.Space.LOCAL) {
  80302. this._decompose();
  80303. this._localRotation.copyFrom(quat);
  80304. this._markAsDirtyAndCompose();
  80305. return;
  80306. }
  80307. var rotMatInv = Bone._tmpMats[0];
  80308. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80309. return;
  80310. }
  80311. var rotMat = Bone._tmpMats[1];
  80312. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80313. rotMatInv.multiplyToRef(rotMat, rotMat);
  80314. this._rotateWithMatrix(rotMat, space, mesh);
  80315. };
  80316. /**
  80317. * Set the rotation matrix of the bone in local of world space
  80318. * @param rotMat The rotation matrix that the bone should be set to
  80319. * @param space The space that the rotation is in
  80320. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80321. */
  80322. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80324. if (space === BABYLON.Space.LOCAL) {
  80325. var quat = Bone._tmpQuat;
  80326. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80327. this.setRotationQuaternion(quat, space, mesh);
  80328. return;
  80329. }
  80330. var rotMatInv = Bone._tmpMats[0];
  80331. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80332. return;
  80333. }
  80334. var rotMat2 = Bone._tmpMats[1];
  80335. rotMat2.copyFrom(rotMat);
  80336. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80337. this._rotateWithMatrix(rotMat2, space, mesh);
  80338. };
  80339. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80340. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80341. var lmat = this.getLocalMatrix();
  80342. var lx = lmat.m[12];
  80343. var ly = lmat.m[13];
  80344. var lz = lmat.m[14];
  80345. var parent = this.getParent();
  80346. var parentScale = Bone._tmpMats[3];
  80347. var parentScaleInv = Bone._tmpMats[4];
  80348. if (parent && space == BABYLON.Space.WORLD) {
  80349. if (mesh) {
  80350. parentScale.copyFrom(mesh.getWorldMatrix());
  80351. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80352. }
  80353. else {
  80354. parentScale.copyFrom(parent.getAbsoluteTransform());
  80355. }
  80356. parentScaleInv.copyFrom(parentScale);
  80357. parentScaleInv.invert();
  80358. lmat.multiplyToRef(parentScale, lmat);
  80359. lmat.multiplyToRef(rmat, lmat);
  80360. lmat.multiplyToRef(parentScaleInv, lmat);
  80361. }
  80362. else {
  80363. if (space == BABYLON.Space.WORLD && mesh) {
  80364. parentScale.copyFrom(mesh.getWorldMatrix());
  80365. parentScaleInv.copyFrom(parentScale);
  80366. parentScaleInv.invert();
  80367. lmat.multiplyToRef(parentScale, lmat);
  80368. lmat.multiplyToRef(rmat, lmat);
  80369. lmat.multiplyToRef(parentScaleInv, lmat);
  80370. }
  80371. else {
  80372. lmat.multiplyToRef(rmat, lmat);
  80373. }
  80374. }
  80375. lmat.m[12] = lx;
  80376. lmat.m[13] = ly;
  80377. lmat.m[14] = lz;
  80378. this.computeAbsoluteTransforms();
  80379. this._markAsDirtyAndDecompose();
  80380. };
  80381. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80382. var scaleMatrix = Bone._tmpMats[2];
  80383. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80384. if (mesh) {
  80385. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80386. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80387. }
  80388. rotMatInv.invert();
  80389. if (isNaN(rotMatInv.m[0])) {
  80390. // Matrix failed to invert.
  80391. // This can happen if scale is zero for example.
  80392. return false;
  80393. }
  80394. scaleMatrix.m[0] *= this._scalingDeterminant;
  80395. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80396. return true;
  80397. };
  80398. /**
  80399. * Get the position of the bone in local or world space
  80400. * @param space The space that the returned position is in
  80401. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80402. * @returns The position of the bone
  80403. */
  80404. Bone.prototype.getPosition = function (space, mesh) {
  80405. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80406. if (mesh === void 0) { mesh = null; }
  80407. var pos = BABYLON.Vector3.Zero();
  80408. this.getPositionToRef(space, mesh, pos);
  80409. return pos;
  80410. };
  80411. /**
  80412. * Copy the position of the bone to a vector3 in local or world space
  80413. * @param space The space that the returned position is in
  80414. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80415. * @param result The vector3 to copy the position to
  80416. */
  80417. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80418. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80419. if (space == BABYLON.Space.LOCAL) {
  80420. var lm = this.getLocalMatrix();
  80421. result.x = lm.m[12];
  80422. result.y = lm.m[13];
  80423. result.z = lm.m[14];
  80424. }
  80425. else {
  80426. var wm = null;
  80427. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80428. if (mesh) {
  80429. wm = mesh.getWorldMatrix();
  80430. }
  80431. this._skeleton.computeAbsoluteTransforms();
  80432. var tmat = Bone._tmpMats[0];
  80433. if (mesh && wm) {
  80434. tmat.copyFrom(this.getAbsoluteTransform());
  80435. tmat.multiplyToRef(wm, tmat);
  80436. }
  80437. else {
  80438. tmat = this.getAbsoluteTransform();
  80439. }
  80440. result.x = tmat.m[12];
  80441. result.y = tmat.m[13];
  80442. result.z = tmat.m[14];
  80443. }
  80444. };
  80445. /**
  80446. * Get the absolute position of the bone (world space)
  80447. * @param mesh The mesh that this bone is attached to
  80448. * @returns The absolute position of the bone
  80449. */
  80450. Bone.prototype.getAbsolutePosition = function (mesh) {
  80451. if (mesh === void 0) { mesh = null; }
  80452. var pos = BABYLON.Vector3.Zero();
  80453. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80454. return pos;
  80455. };
  80456. /**
  80457. * Copy the absolute position of the bone (world space) to the result param
  80458. * @param mesh The mesh that this bone is attached to
  80459. * @param result The vector3 to copy the absolute position to
  80460. */
  80461. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80462. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80463. };
  80464. /**
  80465. * Compute the absolute transforms of this bone and its children
  80466. */
  80467. Bone.prototype.computeAbsoluteTransforms = function () {
  80468. this._compose();
  80469. if (this._parent) {
  80470. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80471. }
  80472. else {
  80473. this._absoluteTransform.copyFrom(this._localMatrix);
  80474. var poseMatrix = this._skeleton.getPoseMatrix();
  80475. if (poseMatrix) {
  80476. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80477. }
  80478. }
  80479. var children = this.children;
  80480. var len = children.length;
  80481. for (var i = 0; i < len; i++) {
  80482. children[i].computeAbsoluteTransforms();
  80483. }
  80484. };
  80485. /**
  80486. * Get the world direction from an axis that is in the local space of the bone
  80487. * @param localAxis The local direction that is used to compute the world direction
  80488. * @param mesh The mesh that this bone is attached to
  80489. * @returns The world direction
  80490. */
  80491. Bone.prototype.getDirection = function (localAxis, mesh) {
  80492. if (mesh === void 0) { mesh = null; }
  80493. var result = BABYLON.Vector3.Zero();
  80494. this.getDirectionToRef(localAxis, mesh, result);
  80495. return result;
  80496. };
  80497. /**
  80498. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80499. * @param localAxis The local direction that is used to compute the world direction
  80500. * @param mesh The mesh that this bone is attached to
  80501. * @param result The vector3 that the world direction will be copied to
  80502. */
  80503. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80504. if (mesh === void 0) { mesh = null; }
  80505. var wm = null;
  80506. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80507. if (mesh) {
  80508. wm = mesh.getWorldMatrix();
  80509. }
  80510. this._skeleton.computeAbsoluteTransforms();
  80511. var mat = Bone._tmpMats[0];
  80512. mat.copyFrom(this.getAbsoluteTransform());
  80513. if (mesh && wm) {
  80514. mat.multiplyToRef(wm, mat);
  80515. }
  80516. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80517. result.normalize();
  80518. };
  80519. /**
  80520. * Get the euler rotation of the bone in local or world space
  80521. * @param space The space that the rotation should be in
  80522. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80523. * @returns The euler rotation
  80524. */
  80525. Bone.prototype.getRotation = function (space, mesh) {
  80526. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80527. if (mesh === void 0) { mesh = null; }
  80528. var result = BABYLON.Vector3.Zero();
  80529. this.getRotationToRef(space, mesh, result);
  80530. return result;
  80531. };
  80532. /**
  80533. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80534. * @param space The space that the rotation should be in
  80535. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80536. * @param result The vector3 that the rotation should be copied to
  80537. */
  80538. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80539. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80540. if (mesh === void 0) { mesh = null; }
  80541. var quat = Bone._tmpQuat;
  80542. this.getRotationQuaternionToRef(space, mesh, quat);
  80543. quat.toEulerAnglesToRef(result);
  80544. };
  80545. /**
  80546. * Get the quaternion rotation of the bone in either local or world space
  80547. * @param space The space that the rotation should be in
  80548. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80549. * @returns The quaternion rotation
  80550. */
  80551. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80552. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80553. if (mesh === void 0) { mesh = null; }
  80554. var result = BABYLON.Quaternion.Identity();
  80555. this.getRotationQuaternionToRef(space, mesh, result);
  80556. return result;
  80557. };
  80558. /**
  80559. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80560. * @param space The space that the rotation should be in
  80561. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80562. * @param result The quaternion that the rotation should be copied to
  80563. */
  80564. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80566. if (mesh === void 0) { mesh = null; }
  80567. if (space == BABYLON.Space.LOCAL) {
  80568. this._decompose();
  80569. result.copyFrom(this._localRotation);
  80570. }
  80571. else {
  80572. var mat = Bone._tmpMats[0];
  80573. var amat = this.getAbsoluteTransform();
  80574. if (mesh) {
  80575. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80576. }
  80577. else {
  80578. mat.copyFrom(amat);
  80579. }
  80580. mat.m[0] *= this._scalingDeterminant;
  80581. mat.m[1] *= this._scalingDeterminant;
  80582. mat.m[2] *= this._scalingDeterminant;
  80583. mat.decompose(undefined, result, undefined);
  80584. }
  80585. };
  80586. /**
  80587. * Get the rotation matrix of the bone in local or world space
  80588. * @param space The space that the rotation should be in
  80589. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80590. * @returns The rotation matrix
  80591. */
  80592. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80593. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80594. var result = BABYLON.Matrix.Identity();
  80595. this.getRotationMatrixToRef(space, mesh, result);
  80596. return result;
  80597. };
  80598. /**
  80599. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80600. * @param space The space that the rotation should be in
  80601. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80602. * @param result The quaternion that the rotation should be copied to
  80603. */
  80604. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80605. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80606. if (space == BABYLON.Space.LOCAL) {
  80607. this.getLocalMatrix().getRotationMatrixToRef(result);
  80608. }
  80609. else {
  80610. var mat = Bone._tmpMats[0];
  80611. var amat = this.getAbsoluteTransform();
  80612. if (mesh) {
  80613. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80614. }
  80615. else {
  80616. mat.copyFrom(amat);
  80617. }
  80618. mat.m[0] *= this._scalingDeterminant;
  80619. mat.m[1] *= this._scalingDeterminant;
  80620. mat.m[2] *= this._scalingDeterminant;
  80621. mat.getRotationMatrixToRef(result);
  80622. }
  80623. };
  80624. /**
  80625. * Get the world position of a point that is in the local space of the bone
  80626. * @param position The local position
  80627. * @param mesh The mesh that this bone is attached to
  80628. * @returns The world position
  80629. */
  80630. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80631. if (mesh === void 0) { mesh = null; }
  80632. var result = BABYLON.Vector3.Zero();
  80633. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80634. return result;
  80635. };
  80636. /**
  80637. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80638. * @param position The local position
  80639. * @param mesh The mesh that this bone is attached to
  80640. * @param result The vector3 that the world position should be copied to
  80641. */
  80642. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80643. if (mesh === void 0) { mesh = null; }
  80644. var wm = null;
  80645. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80646. if (mesh) {
  80647. wm = mesh.getWorldMatrix();
  80648. }
  80649. this._skeleton.computeAbsoluteTransforms();
  80650. var tmat = Bone._tmpMats[0];
  80651. if (mesh && wm) {
  80652. tmat.copyFrom(this.getAbsoluteTransform());
  80653. tmat.multiplyToRef(wm, tmat);
  80654. }
  80655. else {
  80656. tmat = this.getAbsoluteTransform();
  80657. }
  80658. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80659. };
  80660. /**
  80661. * Get the local position of a point that is in world space
  80662. * @param position The world position
  80663. * @param mesh The mesh that this bone is attached to
  80664. * @returns The local position
  80665. */
  80666. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80667. if (mesh === void 0) { mesh = null; }
  80668. var result = BABYLON.Vector3.Zero();
  80669. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80670. return result;
  80671. };
  80672. /**
  80673. * Get the local position of a point that is in world space and copy it to the result param
  80674. * @param position The world position
  80675. * @param mesh The mesh that this bone is attached to
  80676. * @param result The vector3 that the local position should be copied to
  80677. */
  80678. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80679. if (mesh === void 0) { mesh = null; }
  80680. var wm = null;
  80681. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80682. if (mesh) {
  80683. wm = mesh.getWorldMatrix();
  80684. }
  80685. this._skeleton.computeAbsoluteTransforms();
  80686. var tmat = Bone._tmpMats[0];
  80687. tmat.copyFrom(this.getAbsoluteTransform());
  80688. if (mesh && wm) {
  80689. tmat.multiplyToRef(wm, tmat);
  80690. }
  80691. tmat.invert();
  80692. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80693. };
  80694. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80695. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80696. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80697. return Bone;
  80698. }(BABYLON.Node));
  80699. BABYLON.Bone = Bone;
  80700. })(BABYLON || (BABYLON = {}));
  80701. //# sourceMappingURL=babylon.bone.js.map
  80702. var BABYLON;
  80703. (function (BABYLON) {
  80704. /**
  80705. * Class used to apply inverse kinematics to bones
  80706. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80707. */
  80708. var BoneIKController = /** @class */ (function () {
  80709. /**
  80710. * Creates a new BoneIKController
  80711. * @param mesh defines the mesh to control
  80712. * @param bone defines the bone to control
  80713. * @param options defines options to set up the controller
  80714. */
  80715. function BoneIKController(mesh, bone, options) {
  80716. /**
  80717. * Gets or sets the target position
  80718. */
  80719. this.targetPosition = BABYLON.Vector3.Zero();
  80720. /**
  80721. * Gets or sets the pole target position
  80722. */
  80723. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80724. /**
  80725. * Gets or sets the pole target local offset
  80726. */
  80727. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80728. /**
  80729. * Gets or sets the pole angle
  80730. */
  80731. this.poleAngle = 0;
  80732. /**
  80733. * 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)
  80734. */
  80735. this.slerpAmount = 1;
  80736. this._bone1Quat = BABYLON.Quaternion.Identity();
  80737. this._bone1Mat = BABYLON.Matrix.Identity();
  80738. this._bone2Ang = Math.PI;
  80739. this._maxAngle = Math.PI;
  80740. this._rightHandedSystem = false;
  80741. this._bendAxis = BABYLON.Vector3.Right();
  80742. this._slerping = false;
  80743. this._adjustRoll = 0;
  80744. this._bone2 = bone;
  80745. this._bone1 = bone.getParent();
  80746. if (!this._bone1) {
  80747. return;
  80748. }
  80749. this.mesh = mesh;
  80750. var bonePos = bone.getPosition();
  80751. if (bone.getAbsoluteTransform().determinant() > 0) {
  80752. this._rightHandedSystem = true;
  80753. this._bendAxis.x = 0;
  80754. this._bendAxis.y = 0;
  80755. this._bendAxis.z = -1;
  80756. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80757. this._adjustRoll = Math.PI * .5;
  80758. this._bendAxis.z = 1;
  80759. }
  80760. }
  80761. if (this._bone1.length) {
  80762. var boneScale1 = this._bone1.getScale();
  80763. var boneScale2 = this._bone2.getScale();
  80764. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80765. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80766. }
  80767. else if (this._bone1.children[0]) {
  80768. mesh.computeWorldMatrix(true);
  80769. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80770. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80771. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80772. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80773. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80774. }
  80775. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80776. this.maxAngle = Math.PI;
  80777. if (options) {
  80778. if (options.targetMesh) {
  80779. this.targetMesh = options.targetMesh;
  80780. this.targetMesh.computeWorldMatrix(true);
  80781. }
  80782. if (options.poleTargetMesh) {
  80783. this.poleTargetMesh = options.poleTargetMesh;
  80784. this.poleTargetMesh.computeWorldMatrix(true);
  80785. }
  80786. else if (options.poleTargetBone) {
  80787. this.poleTargetBone = options.poleTargetBone;
  80788. }
  80789. else if (this._bone1.getParent()) {
  80790. this.poleTargetBone = this._bone1.getParent();
  80791. }
  80792. if (options.poleTargetLocalOffset) {
  80793. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80794. }
  80795. if (options.poleAngle) {
  80796. this.poleAngle = options.poleAngle;
  80797. }
  80798. if (options.bendAxis) {
  80799. this._bendAxis.copyFrom(options.bendAxis);
  80800. }
  80801. if (options.maxAngle) {
  80802. this.maxAngle = options.maxAngle;
  80803. }
  80804. if (options.slerpAmount) {
  80805. this.slerpAmount = options.slerpAmount;
  80806. }
  80807. }
  80808. }
  80809. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80810. /**
  80811. * Gets or sets maximum allowed angle
  80812. */
  80813. get: function () {
  80814. return this._maxAngle;
  80815. },
  80816. set: function (value) {
  80817. this._setMaxAngle(value);
  80818. },
  80819. enumerable: true,
  80820. configurable: true
  80821. });
  80822. BoneIKController.prototype._setMaxAngle = function (ang) {
  80823. if (ang < 0) {
  80824. ang = 0;
  80825. }
  80826. if (ang > Math.PI || ang == undefined) {
  80827. ang = Math.PI;
  80828. }
  80829. this._maxAngle = ang;
  80830. var a = this._bone1Length;
  80831. var b = this._bone2Length;
  80832. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80833. };
  80834. /**
  80835. * Force the controller to update the bones
  80836. */
  80837. BoneIKController.prototype.update = function () {
  80838. var bone1 = this._bone1;
  80839. if (!bone1) {
  80840. return;
  80841. }
  80842. var target = this.targetPosition;
  80843. var poleTarget = this.poleTargetPosition;
  80844. var mat1 = BoneIKController._tmpMats[0];
  80845. var mat2 = BoneIKController._tmpMats[1];
  80846. if (this.targetMesh) {
  80847. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80848. }
  80849. if (this.poleTargetBone) {
  80850. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80851. }
  80852. else if (this.poleTargetMesh) {
  80853. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80854. }
  80855. var bonePos = BoneIKController._tmpVecs[0];
  80856. var zaxis = BoneIKController._tmpVecs[1];
  80857. var xaxis = BoneIKController._tmpVecs[2];
  80858. var yaxis = BoneIKController._tmpVecs[3];
  80859. var upAxis = BoneIKController._tmpVecs[4];
  80860. var _tmpQuat = BoneIKController._tmpQuat;
  80861. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80862. poleTarget.subtractToRef(bonePos, upAxis);
  80863. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80864. upAxis.y = 1;
  80865. }
  80866. else {
  80867. upAxis.normalize();
  80868. }
  80869. target.subtractToRef(bonePos, yaxis);
  80870. yaxis.normalize();
  80871. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80872. zaxis.normalize();
  80873. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80874. xaxis.normalize();
  80875. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80876. var a = this._bone1Length;
  80877. var b = this._bone2Length;
  80878. var c = BABYLON.Vector3.Distance(bonePos, target);
  80879. if (this._maxReach > 0) {
  80880. c = Math.min(this._maxReach, c);
  80881. }
  80882. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80883. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80884. if (acosa > 1) {
  80885. acosa = 1;
  80886. }
  80887. if (acosb > 1) {
  80888. acosb = 1;
  80889. }
  80890. if (acosa < -1) {
  80891. acosa = -1;
  80892. }
  80893. if (acosb < -1) {
  80894. acosb = -1;
  80895. }
  80896. var angA = Math.acos(acosa);
  80897. var angB = Math.acos(acosb);
  80898. var angC = -angA - angB;
  80899. if (this._rightHandedSystem) {
  80900. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80901. mat2.multiplyToRef(mat1, mat1);
  80902. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80903. mat2.multiplyToRef(mat1, mat1);
  80904. }
  80905. else {
  80906. var _tmpVec = BoneIKController._tmpVecs[5];
  80907. _tmpVec.copyFrom(this._bendAxis);
  80908. _tmpVec.x *= -1;
  80909. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80910. mat2.multiplyToRef(mat1, mat1);
  80911. }
  80912. if (this.poleAngle) {
  80913. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80914. mat1.multiplyToRef(mat2, mat1);
  80915. }
  80916. if (this._bone1) {
  80917. if (this.slerpAmount < 1) {
  80918. if (!this._slerping) {
  80919. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80920. }
  80921. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80922. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80923. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80924. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80925. this._slerping = true;
  80926. }
  80927. else {
  80928. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80929. this._bone1Mat.copyFrom(mat1);
  80930. this._slerping = false;
  80931. }
  80932. }
  80933. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80934. this._bone2Ang = angC;
  80935. };
  80936. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80937. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80938. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80939. return BoneIKController;
  80940. }());
  80941. BABYLON.BoneIKController = BoneIKController;
  80942. })(BABYLON || (BABYLON = {}));
  80943. //# sourceMappingURL=babylon.boneIKController.js.map
  80944. var BABYLON;
  80945. (function (BABYLON) {
  80946. /**
  80947. * Class used to make a bone look toward a point in space
  80948. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80949. */
  80950. var BoneLookController = /** @class */ (function () {
  80951. /**
  80952. * Create a BoneLookController
  80953. * @param mesh the mesh that the bone belongs to
  80954. * @param bone the bone that will be looking to the target
  80955. * @param target the target Vector3 to look at
  80956. * @param settings optional settings:
  80957. * * maxYaw: the maximum angle the bone will yaw to
  80958. * * minYaw: the minimum angle the bone will yaw to
  80959. * * maxPitch: the maximum angle the bone will pitch to
  80960. * * minPitch: the minimum angle the bone will yaw to
  80961. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80962. * * upAxis: the up axis of the coordinate system
  80963. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80964. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80965. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80966. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80967. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80968. * * adjustRoll: used to make an adjustment to the roll of the bone
  80969. **/
  80970. function BoneLookController(mesh, bone, target, options) {
  80971. /**
  80972. * The up axis of the coordinate system that is used when the bone is rotated
  80973. */
  80974. this.upAxis = BABYLON.Vector3.Up();
  80975. /**
  80976. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80977. */
  80978. this.upAxisSpace = BABYLON.Space.LOCAL;
  80979. /**
  80980. * Used to make an adjustment to the yaw of the bone
  80981. */
  80982. this.adjustYaw = 0;
  80983. /**
  80984. * Used to make an adjustment to the pitch of the bone
  80985. */
  80986. this.adjustPitch = 0;
  80987. /**
  80988. * Used to make an adjustment to the roll of the bone
  80989. */
  80990. this.adjustRoll = 0;
  80991. /**
  80992. * 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)
  80993. */
  80994. this.slerpAmount = 1;
  80995. this._boneQuat = BABYLON.Quaternion.Identity();
  80996. this._slerping = false;
  80997. this._firstFrameSkipped = false;
  80998. this._fowardAxis = BABYLON.Vector3.Forward();
  80999. this.mesh = mesh;
  81000. this.bone = bone;
  81001. this.target = target;
  81002. if (options) {
  81003. if (options.adjustYaw) {
  81004. this.adjustYaw = options.adjustYaw;
  81005. }
  81006. if (options.adjustPitch) {
  81007. this.adjustPitch = options.adjustPitch;
  81008. }
  81009. if (options.adjustRoll) {
  81010. this.adjustRoll = options.adjustRoll;
  81011. }
  81012. if (options.maxYaw != null) {
  81013. this.maxYaw = options.maxYaw;
  81014. }
  81015. else {
  81016. this.maxYaw = Math.PI;
  81017. }
  81018. if (options.minYaw != null) {
  81019. this.minYaw = options.minYaw;
  81020. }
  81021. else {
  81022. this.minYaw = -Math.PI;
  81023. }
  81024. if (options.maxPitch != null) {
  81025. this.maxPitch = options.maxPitch;
  81026. }
  81027. else {
  81028. this.maxPitch = Math.PI;
  81029. }
  81030. if (options.minPitch != null) {
  81031. this.minPitch = options.minPitch;
  81032. }
  81033. else {
  81034. this.minPitch = -Math.PI;
  81035. }
  81036. if (options.slerpAmount != null) {
  81037. this.slerpAmount = options.slerpAmount;
  81038. }
  81039. if (options.upAxis != null) {
  81040. this.upAxis = options.upAxis;
  81041. }
  81042. if (options.upAxisSpace != null) {
  81043. this.upAxisSpace = options.upAxisSpace;
  81044. }
  81045. if (options.yawAxis != null || options.pitchAxis != null) {
  81046. var newYawAxis = BABYLON.Axis.Y;
  81047. var newPitchAxis = BABYLON.Axis.X;
  81048. if (options.yawAxis != null) {
  81049. newYawAxis = options.yawAxis.clone();
  81050. newYawAxis.normalize();
  81051. }
  81052. if (options.pitchAxis != null) {
  81053. newPitchAxis = options.pitchAxis.clone();
  81054. newPitchAxis.normalize();
  81055. }
  81056. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  81057. this._transformYawPitch = BABYLON.Matrix.Identity();
  81058. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  81059. this._transformYawPitchInv = this._transformYawPitch.clone();
  81060. this._transformYawPitch.invert();
  81061. }
  81062. }
  81063. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  81064. this.upAxisSpace = BABYLON.Space.LOCAL;
  81065. }
  81066. }
  81067. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  81068. /**
  81069. * Gets or sets the minimum yaw angle that the bone can look to
  81070. */
  81071. get: function () {
  81072. return this._minYaw;
  81073. },
  81074. set: function (value) {
  81075. this._minYaw = value;
  81076. this._minYawSin = Math.sin(value);
  81077. this._minYawCos = Math.cos(value);
  81078. if (this._maxYaw != null) {
  81079. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81080. this._yawRange = this._maxYaw - this._minYaw;
  81081. }
  81082. },
  81083. enumerable: true,
  81084. configurable: true
  81085. });
  81086. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  81087. /**
  81088. * Gets or sets the maximum yaw angle that the bone can look to
  81089. */
  81090. get: function () {
  81091. return this._maxYaw;
  81092. },
  81093. set: function (value) {
  81094. this._maxYaw = value;
  81095. this._maxYawSin = Math.sin(value);
  81096. this._maxYawCos = Math.cos(value);
  81097. if (this._minYaw != null) {
  81098. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81099. this._yawRange = this._maxYaw - this._minYaw;
  81100. }
  81101. },
  81102. enumerable: true,
  81103. configurable: true
  81104. });
  81105. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  81106. /**
  81107. * Gets or sets the minimum pitch angle that the bone can look to
  81108. */
  81109. get: function () {
  81110. return this._minPitch;
  81111. },
  81112. set: function (value) {
  81113. this._minPitch = value;
  81114. this._minPitchTan = Math.tan(value);
  81115. },
  81116. enumerable: true,
  81117. configurable: true
  81118. });
  81119. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  81120. /**
  81121. * Gets or sets the maximum pitch angle that the bone can look to
  81122. */
  81123. get: function () {
  81124. return this._maxPitch;
  81125. },
  81126. set: function (value) {
  81127. this._maxPitch = value;
  81128. this._maxPitchTan = Math.tan(value);
  81129. },
  81130. enumerable: true,
  81131. configurable: true
  81132. });
  81133. /**
  81134. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  81135. */
  81136. BoneLookController.prototype.update = function () {
  81137. //skip the first frame when slerping so that the mesh rotation is correct
  81138. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  81139. this._firstFrameSkipped = true;
  81140. return;
  81141. }
  81142. var bone = this.bone;
  81143. var bonePos = BoneLookController._tmpVecs[0];
  81144. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  81145. var target = this.target;
  81146. var _tmpMat1 = BoneLookController._tmpMats[0];
  81147. var _tmpMat2 = BoneLookController._tmpMats[1];
  81148. var mesh = this.mesh;
  81149. var parentBone = bone.getParent();
  81150. var upAxis = BoneLookController._tmpVecs[1];
  81151. upAxis.copyFrom(this.upAxis);
  81152. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  81153. if (this._transformYawPitch) {
  81154. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  81155. }
  81156. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  81157. }
  81158. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  81159. mesh.getDirectionToRef(upAxis, upAxis);
  81160. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  81161. upAxis.normalize();
  81162. }
  81163. }
  81164. var checkYaw = false;
  81165. var checkPitch = false;
  81166. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  81167. checkYaw = true;
  81168. }
  81169. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  81170. checkPitch = true;
  81171. }
  81172. if (checkYaw || checkPitch) {
  81173. var spaceMat = BoneLookController._tmpMats[2];
  81174. var spaceMatInv = BoneLookController._tmpMats[3];
  81175. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  81176. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  81177. }
  81178. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  81179. spaceMat.copyFrom(mesh.getWorldMatrix());
  81180. }
  81181. else {
  81182. var forwardAxis = BoneLookController._tmpVecs[2];
  81183. forwardAxis.copyFrom(this._fowardAxis);
  81184. if (this._transformYawPitch) {
  81185. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  81186. }
  81187. if (parentBone) {
  81188. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  81189. }
  81190. else {
  81191. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  81192. }
  81193. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  81194. rightAxis.normalize();
  81195. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  81196. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  81197. }
  81198. spaceMat.invertToRef(spaceMatInv);
  81199. var xzlen = null;
  81200. if (checkPitch) {
  81201. var localTarget = BoneLookController._tmpVecs[3];
  81202. target.subtractToRef(bonePos, localTarget);
  81203. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81204. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81205. var pitch = Math.atan2(localTarget.y, xzlen);
  81206. var newPitch = pitch;
  81207. if (pitch > this._maxPitch) {
  81208. localTarget.y = this._maxPitchTan * xzlen;
  81209. newPitch = this._maxPitch;
  81210. }
  81211. else if (pitch < this._minPitch) {
  81212. localTarget.y = this._minPitchTan * xzlen;
  81213. newPitch = this._minPitch;
  81214. }
  81215. if (pitch != newPitch) {
  81216. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81217. localTarget.addInPlace(bonePos);
  81218. target = localTarget;
  81219. }
  81220. }
  81221. if (checkYaw) {
  81222. var localTarget = BoneLookController._tmpVecs[4];
  81223. target.subtractToRef(bonePos, localTarget);
  81224. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81225. var yaw = Math.atan2(localTarget.x, localTarget.z);
  81226. var newYaw = yaw;
  81227. if (yaw > this._maxYaw || yaw < this._minYaw) {
  81228. if (xzlen == null) {
  81229. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81230. }
  81231. if (this._yawRange > Math.PI) {
  81232. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  81233. localTarget.z = this._maxYawCos * xzlen;
  81234. localTarget.x = this._maxYawSin * xzlen;
  81235. newYaw = this._maxYaw;
  81236. }
  81237. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  81238. localTarget.z = this._minYawCos * xzlen;
  81239. localTarget.x = this._minYawSin * xzlen;
  81240. newYaw = this._minYaw;
  81241. }
  81242. }
  81243. else {
  81244. if (yaw > this._maxYaw) {
  81245. localTarget.z = this._maxYawCos * xzlen;
  81246. localTarget.x = this._maxYawSin * xzlen;
  81247. newYaw = this._maxYaw;
  81248. }
  81249. else if (yaw < this._minYaw) {
  81250. localTarget.z = this._minYawCos * xzlen;
  81251. localTarget.x = this._minYawSin * xzlen;
  81252. newYaw = this._minYaw;
  81253. }
  81254. }
  81255. }
  81256. if (this._slerping && this._yawRange > Math.PI) {
  81257. //are we going to be crossing into the min/max region?
  81258. var boneFwd = BoneLookController._tmpVecs[8];
  81259. boneFwd.copyFrom(BABYLON.Axis.Z);
  81260. if (this._transformYawPitch) {
  81261. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81262. }
  81263. var boneRotMat = BoneLookController._tmpMats[4];
  81264. this._boneQuat.toRotationMatrix(boneRotMat);
  81265. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81266. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81267. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81268. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81269. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81270. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81271. if (angBtwTar > angBtwMidYaw) {
  81272. if (xzlen == null) {
  81273. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81274. }
  81275. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81276. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81277. if (angBtwMin < angBtwMax) {
  81278. newYaw = boneYaw + Math.PI * .75;
  81279. localTarget.z = Math.cos(newYaw) * xzlen;
  81280. localTarget.x = Math.sin(newYaw) * xzlen;
  81281. }
  81282. else {
  81283. newYaw = boneYaw - Math.PI * .75;
  81284. localTarget.z = Math.cos(newYaw) * xzlen;
  81285. localTarget.x = Math.sin(newYaw) * xzlen;
  81286. }
  81287. }
  81288. }
  81289. if (yaw != newYaw) {
  81290. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81291. localTarget.addInPlace(bonePos);
  81292. target = localTarget;
  81293. }
  81294. }
  81295. }
  81296. var zaxis = BoneLookController._tmpVecs[5];
  81297. var xaxis = BoneLookController._tmpVecs[6];
  81298. var yaxis = BoneLookController._tmpVecs[7];
  81299. var _tmpQuat = BoneLookController._tmpQuat;
  81300. target.subtractToRef(bonePos, zaxis);
  81301. zaxis.normalize();
  81302. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81303. xaxis.normalize();
  81304. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81305. yaxis.normalize();
  81306. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81307. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81308. return;
  81309. }
  81310. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81311. return;
  81312. }
  81313. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81314. return;
  81315. }
  81316. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81317. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81318. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81319. }
  81320. if (this.slerpAmount < 1) {
  81321. if (!this._slerping) {
  81322. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81323. }
  81324. if (this._transformYawPitch) {
  81325. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81326. }
  81327. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81328. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81329. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81330. this._slerping = true;
  81331. }
  81332. else {
  81333. if (this._transformYawPitch) {
  81334. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81335. }
  81336. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81337. this._slerping = false;
  81338. }
  81339. };
  81340. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81341. var angDiff = ang2 - ang1;
  81342. angDiff %= Math.PI * 2;
  81343. if (angDiff > Math.PI) {
  81344. angDiff -= Math.PI * 2;
  81345. }
  81346. else if (angDiff < -Math.PI) {
  81347. angDiff += Math.PI * 2;
  81348. }
  81349. return angDiff;
  81350. };
  81351. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81352. ang1 %= (2 * Math.PI);
  81353. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81354. ang2 %= (2 * Math.PI);
  81355. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81356. var ab = 0;
  81357. if (ang1 < ang2) {
  81358. ab = ang2 - ang1;
  81359. }
  81360. else {
  81361. ab = ang1 - ang2;
  81362. }
  81363. if (ab > Math.PI) {
  81364. ab = Math.PI * 2 - ab;
  81365. }
  81366. return ab;
  81367. };
  81368. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81369. ang %= (2 * Math.PI);
  81370. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81371. ang1 %= (2 * Math.PI);
  81372. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81373. ang2 %= (2 * Math.PI);
  81374. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81375. if (ang1 < ang2) {
  81376. if (ang > ang1 && ang < ang2) {
  81377. return true;
  81378. }
  81379. }
  81380. else {
  81381. if (ang > ang2 && ang < ang1) {
  81382. return true;
  81383. }
  81384. }
  81385. return false;
  81386. };
  81387. 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()];
  81388. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81389. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81390. return BoneLookController;
  81391. }());
  81392. BABYLON.BoneLookController = BoneLookController;
  81393. })(BABYLON || (BABYLON = {}));
  81394. //# sourceMappingURL=babylon.boneLookController.js.map
  81395. var BABYLON;
  81396. (function (BABYLON) {
  81397. /**
  81398. * Class used to handle skinning animations
  81399. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81400. */
  81401. var Skeleton = /** @class */ (function () {
  81402. /**
  81403. * Creates a new skeleton
  81404. * @param name defines the skeleton name
  81405. * @param id defines the skeleton Id
  81406. * @param scene defines the hosting scene
  81407. */
  81408. function Skeleton(
  81409. /** defines the skeleton name */
  81410. name,
  81411. /** defines the skeleton Id */
  81412. id, scene) {
  81413. this.name = name;
  81414. this.id = id;
  81415. /**
  81416. * Gets the list of child bones
  81417. */
  81418. this.bones = new Array();
  81419. /**
  81420. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81421. */
  81422. this.needInitialSkinMatrix = false;
  81423. this._isDirty = true;
  81424. this._meshesWithPoseMatrix = new Array();
  81425. this._identity = BABYLON.Matrix.Identity();
  81426. this._ranges = {};
  81427. this._lastAbsoluteTransformsUpdateId = -1;
  81428. /**
  81429. * Specifies if the skeleton should be serialized
  81430. */
  81431. this.doNotSerialize = false;
  81432. this._animationPropertiesOverride = null;
  81433. // Events
  81434. /**
  81435. * An observable triggered before computing the skeleton's matrices
  81436. */
  81437. this.onBeforeComputeObservable = new BABYLON.Observable();
  81438. this.bones = [];
  81439. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81440. scene.skeletons.push(this);
  81441. //make sure it will recalculate the matrix next time prepare is called.
  81442. this._isDirty = true;
  81443. }
  81444. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81445. /**
  81446. * Gets or sets the animation properties override
  81447. */
  81448. get: function () {
  81449. if (!this._animationPropertiesOverride) {
  81450. return this._scene.animationPropertiesOverride;
  81451. }
  81452. return this._animationPropertiesOverride;
  81453. },
  81454. set: function (value) {
  81455. this._animationPropertiesOverride = value;
  81456. },
  81457. enumerable: true,
  81458. configurable: true
  81459. });
  81460. // Members
  81461. /**
  81462. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81463. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81464. * @returns a Float32Array containing matrices data
  81465. */
  81466. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81467. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81468. return mesh._bonesTransformMatrices;
  81469. }
  81470. if (!this._transformMatrices) {
  81471. this.prepare();
  81472. }
  81473. return this._transformMatrices;
  81474. };
  81475. /**
  81476. * Gets the current hosting scene
  81477. * @returns a scene object
  81478. */
  81479. Skeleton.prototype.getScene = function () {
  81480. return this._scene;
  81481. };
  81482. // Methods
  81483. /**
  81484. * Gets a string representing the current skeleton data
  81485. * @param fullDetails defines a boolean indicating if we want a verbose version
  81486. * @returns a string representing the current skeleton data
  81487. */
  81488. Skeleton.prototype.toString = function (fullDetails) {
  81489. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81490. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81491. if (fullDetails) {
  81492. ret += ", Ranges: {";
  81493. var first = true;
  81494. for (var name_1 in this._ranges) {
  81495. if (first) {
  81496. ret += ", ";
  81497. first = false;
  81498. }
  81499. ret += name_1;
  81500. }
  81501. ret += "}";
  81502. }
  81503. return ret;
  81504. };
  81505. /**
  81506. * Get bone's index searching by name
  81507. * @param name defines bone's name to search for
  81508. * @return the indice of the bone. Returns -1 if not found
  81509. */
  81510. Skeleton.prototype.getBoneIndexByName = function (name) {
  81511. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81512. if (this.bones[boneIndex].name === name) {
  81513. return boneIndex;
  81514. }
  81515. }
  81516. return -1;
  81517. };
  81518. /**
  81519. * Creater a new animation range
  81520. * @param name defines the name of the range
  81521. * @param from defines the start key
  81522. * @param to defines the end key
  81523. */
  81524. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81525. // check name not already in use
  81526. if (!this._ranges[name]) {
  81527. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81528. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81529. if (this.bones[i].animations[0]) {
  81530. this.bones[i].animations[0].createRange(name, from, to);
  81531. }
  81532. }
  81533. }
  81534. };
  81535. /**
  81536. * Delete a specific animation range
  81537. * @param name defines the name of the range
  81538. * @param deleteFrames defines if frames must be removed as well
  81539. */
  81540. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81541. if (deleteFrames === void 0) { deleteFrames = true; }
  81542. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81543. if (this.bones[i].animations[0]) {
  81544. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81545. }
  81546. }
  81547. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81548. };
  81549. /**
  81550. * Gets a specific animation range
  81551. * @param name defines the name of the range to look for
  81552. * @returns the requested animation range or null if not found
  81553. */
  81554. Skeleton.prototype.getAnimationRange = function (name) {
  81555. return this._ranges[name];
  81556. };
  81557. /**
  81558. * Gets the list of all animation ranges defined on this skeleton
  81559. * @returns an array
  81560. */
  81561. Skeleton.prototype.getAnimationRanges = function () {
  81562. var animationRanges = [];
  81563. var name;
  81564. var i = 0;
  81565. for (name in this._ranges) {
  81566. animationRanges[i] = this._ranges[name];
  81567. i++;
  81568. }
  81569. return animationRanges;
  81570. };
  81571. /**
  81572. * Copy animation range from a source skeleton.
  81573. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81574. * @param source defines the source skeleton
  81575. * @param name defines the name of the range to copy
  81576. * @param rescaleAsRequired defines if rescaling must be applied if required
  81577. * @returns true if operation was successful
  81578. */
  81579. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81580. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81581. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81582. return false;
  81583. }
  81584. var ret = true;
  81585. var frameOffset = this._getHighestAnimationFrame() + 1;
  81586. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81587. var boneDict = {};
  81588. var sourceBones = source.bones;
  81589. var nBones;
  81590. var i;
  81591. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81592. boneDict[sourceBones[i].name] = sourceBones[i];
  81593. }
  81594. if (this.bones.length !== sourceBones.length) {
  81595. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81596. ret = false;
  81597. }
  81598. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81599. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81600. var boneName = this.bones[i].name;
  81601. var sourceBone = boneDict[boneName];
  81602. if (sourceBone) {
  81603. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81604. }
  81605. else {
  81606. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81607. ret = false;
  81608. }
  81609. }
  81610. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81611. var range = source.getAnimationRange(name);
  81612. if (range) {
  81613. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81614. }
  81615. return ret;
  81616. };
  81617. /**
  81618. * Forces the skeleton to go to rest pose
  81619. */
  81620. Skeleton.prototype.returnToRest = function () {
  81621. for (var index = 0; index < this.bones.length; index++) {
  81622. this.bones[index].returnToRest();
  81623. }
  81624. };
  81625. Skeleton.prototype._getHighestAnimationFrame = function () {
  81626. var ret = 0;
  81627. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81628. if (this.bones[i].animations[0]) {
  81629. var highest = this.bones[i].animations[0].getHighestFrame();
  81630. if (ret < highest) {
  81631. ret = highest;
  81632. }
  81633. }
  81634. }
  81635. return ret;
  81636. };
  81637. /**
  81638. * Begin a specific animation range
  81639. * @param name defines the name of the range to start
  81640. * @param loop defines if looping must be turned on (false by default)
  81641. * @param speedRatio defines the speed ratio to apply (1 by default)
  81642. * @param onAnimationEnd defines a callback which will be called when animation will end
  81643. * @returns a new animatable
  81644. */
  81645. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81646. var range = this.getAnimationRange(name);
  81647. if (!range) {
  81648. return null;
  81649. }
  81650. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81651. };
  81652. /** @hidden */
  81653. Skeleton.prototype._markAsDirty = function () {
  81654. this._isDirty = true;
  81655. };
  81656. /** @hidden */
  81657. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81658. this._meshesWithPoseMatrix.push(mesh);
  81659. };
  81660. /** @hidden */
  81661. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81662. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81663. if (index > -1) {
  81664. this._meshesWithPoseMatrix.splice(index, 1);
  81665. }
  81666. };
  81667. /** @hidden */
  81668. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81669. this.onBeforeComputeObservable.notifyObservers(this);
  81670. for (var index = 0; index < this.bones.length; index++) {
  81671. var bone = this.bones[index];
  81672. var parentBone = bone.getParent();
  81673. if (parentBone) {
  81674. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81675. }
  81676. else {
  81677. if (initialSkinMatrix) {
  81678. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81679. }
  81680. else {
  81681. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81682. }
  81683. }
  81684. if (bone._index !== -1) {
  81685. var mappedIndex = bone._index === null ? index : bone._index;
  81686. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81687. }
  81688. }
  81689. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81690. };
  81691. /**
  81692. * Build all resources required to render a skeleton
  81693. */
  81694. Skeleton.prototype.prepare = function () {
  81695. if (!this._isDirty) {
  81696. return;
  81697. }
  81698. if (this.needInitialSkinMatrix) {
  81699. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81700. var mesh = this._meshesWithPoseMatrix[index];
  81701. var poseMatrix = mesh.getPoseMatrix();
  81702. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81703. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81704. }
  81705. if (this._synchronizedWithMesh !== mesh) {
  81706. this._synchronizedWithMesh = mesh;
  81707. // Prepare bones
  81708. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81709. var bone = this.bones[boneIndex];
  81710. if (!bone.getParent()) {
  81711. var matrix = bone.getBaseMatrix();
  81712. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81713. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81714. }
  81715. }
  81716. }
  81717. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81718. }
  81719. }
  81720. else {
  81721. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81722. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81723. }
  81724. this._computeTransformMatrices(this._transformMatrices, null);
  81725. }
  81726. this._isDirty = false;
  81727. this._scene._activeBones.addCount(this.bones.length, false);
  81728. };
  81729. /**
  81730. * Gets the list of animatables currently running for this skeleton
  81731. * @returns an array of animatables
  81732. */
  81733. Skeleton.prototype.getAnimatables = function () {
  81734. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81735. this._animatables = [];
  81736. for (var index = 0; index < this.bones.length; index++) {
  81737. this._animatables.push(this.bones[index]);
  81738. }
  81739. }
  81740. return this._animatables;
  81741. };
  81742. /**
  81743. * Clone the current skeleton
  81744. * @param name defines the name of the new skeleton
  81745. * @param id defines the id of the enw skeleton
  81746. * @returns the new skeleton
  81747. */
  81748. Skeleton.prototype.clone = function (name, id) {
  81749. var result = new Skeleton(name, id || name, this._scene);
  81750. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81751. for (var index = 0; index < this.bones.length; index++) {
  81752. var source = this.bones[index];
  81753. var parentBone = null;
  81754. var parent_1 = source.getParent();
  81755. if (parent_1) {
  81756. var parentIndex = this.bones.indexOf(parent_1);
  81757. parentBone = result.bones[parentIndex];
  81758. }
  81759. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81760. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81761. }
  81762. if (this._ranges) {
  81763. result._ranges = {};
  81764. for (var rangeName in this._ranges) {
  81765. var range = this._ranges[rangeName];
  81766. if (range) {
  81767. result._ranges[rangeName] = range.clone();
  81768. }
  81769. }
  81770. }
  81771. this._isDirty = true;
  81772. return result;
  81773. };
  81774. /**
  81775. * Enable animation blending for this skeleton
  81776. * @param blendingSpeed defines the blending speed to apply
  81777. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81778. */
  81779. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81780. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81781. this.bones.forEach(function (bone) {
  81782. bone.animations.forEach(function (animation) {
  81783. animation.enableBlending = true;
  81784. animation.blendingSpeed = blendingSpeed;
  81785. });
  81786. });
  81787. };
  81788. /**
  81789. * Releases all resources associated with the current skeleton
  81790. */
  81791. Skeleton.prototype.dispose = function () {
  81792. this._meshesWithPoseMatrix = [];
  81793. // Animations
  81794. this.getScene().stopAnimation(this);
  81795. // Remove from scene
  81796. this.getScene().removeSkeleton(this);
  81797. };
  81798. /**
  81799. * Serialize the skeleton in a JSON object
  81800. * @returns a JSON object
  81801. */
  81802. Skeleton.prototype.serialize = function () {
  81803. var serializationObject = {};
  81804. serializationObject.name = this.name;
  81805. serializationObject.id = this.id;
  81806. if (this.dimensionsAtRest) {
  81807. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81808. }
  81809. serializationObject.bones = [];
  81810. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81811. for (var index = 0; index < this.bones.length; index++) {
  81812. var bone = this.bones[index];
  81813. var parent_2 = bone.getParent();
  81814. var serializedBone = {
  81815. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81816. name: bone.name,
  81817. matrix: bone.getBaseMatrix().toArray(),
  81818. rest: bone.getRestPose().toArray()
  81819. };
  81820. serializationObject.bones.push(serializedBone);
  81821. if (bone.length) {
  81822. serializedBone.length = bone.length;
  81823. }
  81824. if (bone.metadata) {
  81825. serializedBone.metadata = bone.metadata;
  81826. }
  81827. if (bone.animations && bone.animations.length > 0) {
  81828. serializedBone.animation = bone.animations[0].serialize();
  81829. }
  81830. serializationObject.ranges = [];
  81831. for (var name in this._ranges) {
  81832. var source = this._ranges[name];
  81833. if (!source) {
  81834. continue;
  81835. }
  81836. var range = {};
  81837. range.name = name;
  81838. range.from = source.from;
  81839. range.to = source.to;
  81840. serializationObject.ranges.push(range);
  81841. }
  81842. }
  81843. return serializationObject;
  81844. };
  81845. /**
  81846. * Creates a new skeleton from serialized data
  81847. * @param parsedSkeleton defines the serialized data
  81848. * @param scene defines the hosting scene
  81849. * @returns a new skeleton
  81850. */
  81851. Skeleton.Parse = function (parsedSkeleton, scene) {
  81852. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81853. if (parsedSkeleton.dimensionsAtRest) {
  81854. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81855. }
  81856. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81857. var index;
  81858. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81859. var parsedBone = parsedSkeleton.bones[index];
  81860. var parentBone = null;
  81861. if (parsedBone.parentBoneIndex > -1) {
  81862. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81863. }
  81864. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81865. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81866. if (parsedBone.length) {
  81867. bone.length = parsedBone.length;
  81868. }
  81869. if (parsedBone.metadata) {
  81870. bone.metadata = parsedBone.metadata;
  81871. }
  81872. if (parsedBone.animation) {
  81873. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81874. }
  81875. }
  81876. // placed after bones, so createAnimationRange can cascade down
  81877. if (parsedSkeleton.ranges) {
  81878. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81879. var data = parsedSkeleton.ranges[index];
  81880. skeleton.createAnimationRange(data.name, data.from, data.to);
  81881. }
  81882. }
  81883. return skeleton;
  81884. };
  81885. /**
  81886. * Compute all node absolute transforms
  81887. * @param forceUpdate defines if computation must be done even if cache is up to date
  81888. */
  81889. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81890. if (forceUpdate === void 0) { forceUpdate = false; }
  81891. var renderId = this._scene.getRenderId();
  81892. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81893. this.bones[0].computeAbsoluteTransforms();
  81894. this._lastAbsoluteTransformsUpdateId = renderId;
  81895. }
  81896. };
  81897. /**
  81898. * Gets the root pose matrix
  81899. * @returns a matrix
  81900. */
  81901. Skeleton.prototype.getPoseMatrix = function () {
  81902. var poseMatrix = null;
  81903. if (this._meshesWithPoseMatrix.length > 0) {
  81904. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81905. }
  81906. return poseMatrix;
  81907. };
  81908. /**
  81909. * Sorts bones per internal index
  81910. */
  81911. Skeleton.prototype.sortBones = function () {
  81912. var bones = new Array();
  81913. var visited = new Array(this.bones.length);
  81914. for (var index = 0; index < this.bones.length; index++) {
  81915. this._sortBones(index, bones, visited);
  81916. }
  81917. this.bones = bones;
  81918. };
  81919. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81920. if (visited[index]) {
  81921. return;
  81922. }
  81923. visited[index] = true;
  81924. var bone = this.bones[index];
  81925. if (bone._index === undefined) {
  81926. bone._index = index;
  81927. }
  81928. var parentBone = bone.getParent();
  81929. if (parentBone) {
  81930. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81931. }
  81932. bones.push(bone);
  81933. };
  81934. return Skeleton;
  81935. }());
  81936. BABYLON.Skeleton = Skeleton;
  81937. })(BABYLON || (BABYLON = {}));
  81938. //# sourceMappingURL=babylon.skeleton.js.map
  81939. var BABYLON;
  81940. (function (BABYLON) {
  81941. /**
  81942. * Class representing spherical polynomial coefficients to the 3rd degree
  81943. */
  81944. var SphericalPolynomial = /** @class */ (function () {
  81945. function SphericalPolynomial() {
  81946. /**
  81947. * The x coefficients of the spherical polynomial
  81948. */
  81949. this.x = BABYLON.Vector3.Zero();
  81950. /**
  81951. * The y coefficients of the spherical polynomial
  81952. */
  81953. this.y = BABYLON.Vector3.Zero();
  81954. /**
  81955. * The z coefficients of the spherical polynomial
  81956. */
  81957. this.z = BABYLON.Vector3.Zero();
  81958. /**
  81959. * The xx coefficients of the spherical polynomial
  81960. */
  81961. this.xx = BABYLON.Vector3.Zero();
  81962. /**
  81963. * The yy coefficients of the spherical polynomial
  81964. */
  81965. this.yy = BABYLON.Vector3.Zero();
  81966. /**
  81967. * The zz coefficients of the spherical polynomial
  81968. */
  81969. this.zz = BABYLON.Vector3.Zero();
  81970. /**
  81971. * The xy coefficients of the spherical polynomial
  81972. */
  81973. this.xy = BABYLON.Vector3.Zero();
  81974. /**
  81975. * The yz coefficients of the spherical polynomial
  81976. */
  81977. this.yz = BABYLON.Vector3.Zero();
  81978. /**
  81979. * The zx coefficients of the spherical polynomial
  81980. */
  81981. this.zx = BABYLON.Vector3.Zero();
  81982. }
  81983. /**
  81984. * Adds an ambient color to the spherical polynomial
  81985. * @param color the color to add
  81986. */
  81987. SphericalPolynomial.prototype.addAmbient = function (color) {
  81988. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81989. this.xx = this.xx.add(colorVector);
  81990. this.yy = this.yy.add(colorVector);
  81991. this.zz = this.zz.add(colorVector);
  81992. };
  81993. /**
  81994. * Scales the spherical polynomial by the given amount
  81995. * @param scale the amount to scale
  81996. */
  81997. SphericalPolynomial.prototype.scale = function (scale) {
  81998. this.x = this.x.scale(scale);
  81999. this.y = this.y.scale(scale);
  82000. this.z = this.z.scale(scale);
  82001. this.xx = this.xx.scale(scale);
  82002. this.yy = this.yy.scale(scale);
  82003. this.zz = this.zz.scale(scale);
  82004. this.yz = this.yz.scale(scale);
  82005. this.zx = this.zx.scale(scale);
  82006. this.xy = this.xy.scale(scale);
  82007. };
  82008. /**
  82009. * Gets the spherical polynomial from harmonics
  82010. * @param harmonics the spherical harmonics
  82011. * @returns the spherical polynomial
  82012. */
  82013. SphericalPolynomial.FromHarmonics = function (harmonics) {
  82014. var result = new SphericalPolynomial();
  82015. result.x = harmonics.l11.scale(1.02333);
  82016. result.y = harmonics.l1_1.scale(1.02333);
  82017. result.z = harmonics.l10.scale(1.02333);
  82018. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  82019. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  82020. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  82021. result.yz = harmonics.l2_1.scale(0.858086);
  82022. result.zx = harmonics.l21.scale(0.858086);
  82023. result.xy = harmonics.l2_2.scale(0.858086);
  82024. result.scale(1.0 / Math.PI);
  82025. return result;
  82026. };
  82027. /**
  82028. * Constructs a spherical polynomial from an array.
  82029. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  82030. * @returns the spherical polynomial
  82031. */
  82032. SphericalPolynomial.FromArray = function (data) {
  82033. var sp = new SphericalPolynomial();
  82034. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  82035. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  82036. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  82037. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  82038. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  82039. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  82040. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  82041. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  82042. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  82043. return sp;
  82044. };
  82045. return SphericalPolynomial;
  82046. }());
  82047. BABYLON.SphericalPolynomial = SphericalPolynomial;
  82048. /**
  82049. * Class representing spherical harmonics coefficients to the 3rd degree
  82050. */
  82051. var SphericalHarmonics = /** @class */ (function () {
  82052. function SphericalHarmonics() {
  82053. /**
  82054. * The l0,0 coefficients of the spherical harmonics
  82055. */
  82056. this.l00 = BABYLON.Vector3.Zero();
  82057. /**
  82058. * The l1,-1 coefficients of the spherical harmonics
  82059. */
  82060. this.l1_1 = BABYLON.Vector3.Zero();
  82061. /**
  82062. * The l1,0 coefficients of the spherical harmonics
  82063. */
  82064. this.l10 = BABYLON.Vector3.Zero();
  82065. /**
  82066. * The l1,1 coefficients of the spherical harmonics
  82067. */
  82068. this.l11 = BABYLON.Vector3.Zero();
  82069. /**
  82070. * The l2,-2 coefficients of the spherical harmonics
  82071. */
  82072. this.l2_2 = BABYLON.Vector3.Zero();
  82073. /**
  82074. * The l2,-1 coefficients of the spherical harmonics
  82075. */
  82076. this.l2_1 = BABYLON.Vector3.Zero();
  82077. /**
  82078. * The l2,0 coefficients of the spherical harmonics
  82079. */
  82080. this.l20 = BABYLON.Vector3.Zero();
  82081. /**
  82082. * The l2,1 coefficients of the spherical harmonics
  82083. */
  82084. this.l21 = BABYLON.Vector3.Zero();
  82085. /**
  82086. * The l2,2 coefficients of the spherical harmonics
  82087. */
  82088. this.lL22 = BABYLON.Vector3.Zero();
  82089. }
  82090. /**
  82091. * Adds a light to the spherical harmonics
  82092. * @param direction the direction of the light
  82093. * @param color the color of the light
  82094. * @param deltaSolidAngle the delta solid angle of the light
  82095. */
  82096. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  82097. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82098. var c = colorVector.scale(deltaSolidAngle);
  82099. this.l00 = this.l00.add(c.scale(0.282095));
  82100. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  82101. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  82102. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  82103. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  82104. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  82105. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  82106. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  82107. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  82108. };
  82109. /**
  82110. * Scales the spherical harmonics by the given amount
  82111. * @param scale the amount to scale
  82112. */
  82113. SphericalHarmonics.prototype.scale = function (scale) {
  82114. this.l00 = this.l00.scale(scale);
  82115. this.l1_1 = this.l1_1.scale(scale);
  82116. this.l10 = this.l10.scale(scale);
  82117. this.l11 = this.l11.scale(scale);
  82118. this.l2_2 = this.l2_2.scale(scale);
  82119. this.l2_1 = this.l2_1.scale(scale);
  82120. this.l20 = this.l20.scale(scale);
  82121. this.l21 = this.l21.scale(scale);
  82122. this.lL22 = this.lL22.scale(scale);
  82123. };
  82124. /**
  82125. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  82126. *
  82127. * ```
  82128. * E_lm = A_l * L_lm
  82129. * ```
  82130. *
  82131. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  82132. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  82133. * the scaling factors are given in equation 9.
  82134. */
  82135. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  82136. // Constant (Band 0)
  82137. this.l00 = this.l00.scale(3.141593);
  82138. // Linear (Band 1)
  82139. this.l1_1 = this.l1_1.scale(2.094395);
  82140. this.l10 = this.l10.scale(2.094395);
  82141. this.l11 = this.l11.scale(2.094395);
  82142. // Quadratic (Band 2)
  82143. this.l2_2 = this.l2_2.scale(0.785398);
  82144. this.l2_1 = this.l2_1.scale(0.785398);
  82145. this.l20 = this.l20.scale(0.785398);
  82146. this.l21 = this.l21.scale(0.785398);
  82147. this.lL22 = this.lL22.scale(0.785398);
  82148. };
  82149. /**
  82150. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82151. *
  82152. * ```
  82153. * L = (1/pi) * E * rho
  82154. * ```
  82155. *
  82156. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82157. */
  82158. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  82159. this.scale(1.0 / Math.PI);
  82160. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82161. // (The pixel shader must apply albedo after texture fetches, etc).
  82162. };
  82163. /**
  82164. * Gets the spherical harmonics from polynomial
  82165. * @param polynomial the spherical polynomial
  82166. * @returns the spherical harmonics
  82167. */
  82168. SphericalHarmonics.FromPolynomial = function (polynomial) {
  82169. var result = new SphericalHarmonics();
  82170. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  82171. result.l1_1 = polynomial.y.scale(0.977204);
  82172. result.l10 = polynomial.z.scale(0.977204);
  82173. result.l11 = polynomial.x.scale(0.977204);
  82174. result.l2_2 = polynomial.xy.scale(1.16538);
  82175. result.l2_1 = polynomial.yz.scale(1.16538);
  82176. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  82177. result.l21 = polynomial.zx.scale(1.16538);
  82178. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  82179. result.scale(Math.PI);
  82180. return result;
  82181. };
  82182. /**
  82183. * Constructs a spherical harmonics from an array.
  82184. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  82185. * @returns the spherical harmonics
  82186. */
  82187. SphericalHarmonics.FromArray = function (data) {
  82188. var sh = new SphericalHarmonics();
  82189. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  82190. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  82191. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  82192. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  82193. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  82194. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  82195. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  82196. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  82197. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  82198. return sh;
  82199. };
  82200. return SphericalHarmonics;
  82201. }());
  82202. BABYLON.SphericalHarmonics = SphericalHarmonics;
  82203. })(BABYLON || (BABYLON = {}));
  82204. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  82205. var BABYLON;
  82206. (function (BABYLON) {
  82207. var FileFaceOrientation = /** @class */ (function () {
  82208. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  82209. this.name = name;
  82210. this.worldAxisForNormal = worldAxisForNormal;
  82211. this.worldAxisForFileX = worldAxisForFileX;
  82212. this.worldAxisForFileY = worldAxisForFileY;
  82213. }
  82214. return FileFaceOrientation;
  82215. }());
  82216. ;
  82217. /**
  82218. * Helper class dealing with the extraction of spherical polynomial dataArray
  82219. * from a cube map.
  82220. */
  82221. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  82222. function CubeMapToSphericalPolynomialTools() {
  82223. }
  82224. /**
  82225. * Converts a texture to the according Spherical Polynomial data.
  82226. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82227. *
  82228. * @param texture The texture to extract the information from.
  82229. * @return The Spherical Polynomial data.
  82230. */
  82231. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  82232. if (!texture.isCube) {
  82233. // Only supports cube Textures currently.
  82234. return null;
  82235. }
  82236. var size = texture.getSize().width;
  82237. var right = texture.readPixels(0);
  82238. var left = texture.readPixels(1);
  82239. var up;
  82240. var down;
  82241. if (texture.isRenderTarget) {
  82242. up = texture.readPixels(3);
  82243. down = texture.readPixels(2);
  82244. }
  82245. else {
  82246. up = texture.readPixels(2);
  82247. down = texture.readPixels(3);
  82248. }
  82249. var front = texture.readPixels(4);
  82250. var back = texture.readPixels(5);
  82251. var gammaSpace = texture.gammaSpace;
  82252. // Always read as RGBA.
  82253. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82254. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82255. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82256. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82257. }
  82258. var cubeInfo = {
  82259. size: size,
  82260. right: right,
  82261. left: left,
  82262. up: up,
  82263. down: down,
  82264. front: front,
  82265. back: back,
  82266. format: format,
  82267. type: type,
  82268. gammaSpace: gammaSpace,
  82269. };
  82270. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  82271. };
  82272. /**
  82273. * Converts a cubemap to the according Spherical Polynomial data.
  82274. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82275. *
  82276. * @param cubeInfo The Cube map to extract the information from.
  82277. * @return The Spherical Polynomial data.
  82278. */
  82279. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82280. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82281. var totalSolidAngle = 0.0;
  82282. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82283. var du = 2.0 / cubeInfo.size;
  82284. var dv = du;
  82285. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82286. var minUV = du * 0.5 - 1.0;
  82287. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82288. var fileFace = this.FileFaces[faceIndex];
  82289. var dataArray = cubeInfo[fileFace.name];
  82290. var v = minUV;
  82291. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82292. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82293. // Because SP is still linear, so summation is fine in that basis.
  82294. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82295. for (var y = 0; y < cubeInfo.size; y++) {
  82296. var u = minUV;
  82297. for (var x = 0; x < cubeInfo.size; x++) {
  82298. // World direction (not normalised)
  82299. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82300. worldDirection.normalize();
  82301. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82302. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82303. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82304. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82305. // Handle Integer types.
  82306. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82307. r /= 255;
  82308. g /= 255;
  82309. b /= 255;
  82310. }
  82311. // Handle Gamma space textures.
  82312. if (cubeInfo.gammaSpace) {
  82313. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82314. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82315. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82316. }
  82317. var color = new BABYLON.Color3(r, g, b);
  82318. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82319. totalSolidAngle += deltaSolidAngle;
  82320. u += du;
  82321. }
  82322. v += dv;
  82323. }
  82324. }
  82325. // Solid angle for entire sphere is 4*pi
  82326. var sphereSolidAngle = 4.0 * Math.PI;
  82327. // Adjust the solid angle to allow for how many faces we processed.
  82328. var facesProcessed = 6.0;
  82329. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82330. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82331. // This is needed because the numerical integration over the cube uses a
  82332. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82333. // and also to compensate for accumulative error due to float precision in the summation.
  82334. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82335. sphericalHarmonics.scale(correctionFactor);
  82336. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82337. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82338. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  82339. };
  82340. CubeMapToSphericalPolynomialTools.FileFaces = [
  82341. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82342. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82343. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82344. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82345. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82346. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82347. ];
  82348. return CubeMapToSphericalPolynomialTools;
  82349. }());
  82350. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82351. })(BABYLON || (BABYLON = {}));
  82352. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82353. var BABYLON;
  82354. (function (BABYLON) {
  82355. /**
  82356. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82357. */
  82358. var PanoramaToCubeMapTools = /** @class */ (function () {
  82359. function PanoramaToCubeMapTools() {
  82360. }
  82361. /**
  82362. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82363. *
  82364. * @param float32Array The source data.
  82365. * @param inputWidth The width of the input panorama.
  82366. * @param inputhHeight The height of the input panorama.
  82367. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82368. * @return The cubemap data
  82369. */
  82370. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82371. if (!float32Array) {
  82372. throw "ConvertPanoramaToCubemap: input cannot be null";
  82373. }
  82374. if (float32Array.length != inputWidth * inputHeight * 3) {
  82375. throw "ConvertPanoramaToCubemap: input size is wrong";
  82376. }
  82377. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82378. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82379. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82380. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82381. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82382. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82383. return {
  82384. front: textureFront,
  82385. back: textureBack,
  82386. left: textureLeft,
  82387. right: textureRight,
  82388. up: textureUp,
  82389. down: textureDown,
  82390. size: size,
  82391. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82392. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82393. gammaSpace: false,
  82394. };
  82395. };
  82396. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82397. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82398. var textureArray = new Float32Array(buffer);
  82399. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82400. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82401. var dy = 1 / texSize;
  82402. var fy = 0;
  82403. for (var y = 0; y < texSize; y++) {
  82404. var xv1 = faceData[0];
  82405. var xv2 = faceData[2];
  82406. for (var x = 0; x < texSize; x++) {
  82407. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82408. v.normalize();
  82409. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82410. // 3 channels per pixels
  82411. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82412. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82413. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82414. xv1 = xv1.add(rotDX1);
  82415. xv2 = xv2.add(rotDX2);
  82416. }
  82417. fy += dy;
  82418. }
  82419. return textureArray;
  82420. };
  82421. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82422. var theta = Math.atan2(vDir.z, vDir.x);
  82423. var phi = Math.acos(vDir.y);
  82424. while (theta < -Math.PI)
  82425. theta += 2 * Math.PI;
  82426. while (theta > Math.PI)
  82427. theta -= 2 * Math.PI;
  82428. var dx = theta / Math.PI;
  82429. var dy = phi / Math.PI;
  82430. // recenter.
  82431. dx = dx * 0.5 + 0.5;
  82432. var px = Math.round(dx * inputWidth);
  82433. if (px < 0)
  82434. px = 0;
  82435. else if (px >= inputWidth)
  82436. px = inputWidth - 1;
  82437. var py = Math.round(dy * inputHeight);
  82438. if (py < 0)
  82439. py = 0;
  82440. else if (py >= inputHeight)
  82441. py = inputHeight - 1;
  82442. var inputY = (inputHeight - py - 1);
  82443. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82444. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82445. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82446. return {
  82447. r: r,
  82448. g: g,
  82449. b: b
  82450. };
  82451. };
  82452. PanoramaToCubeMapTools.FACE_FRONT = [
  82453. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82454. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82455. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82456. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82457. ];
  82458. PanoramaToCubeMapTools.FACE_BACK = [
  82459. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82460. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82461. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82462. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82463. ];
  82464. PanoramaToCubeMapTools.FACE_RIGHT = [
  82465. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82466. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82467. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82468. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82469. ];
  82470. PanoramaToCubeMapTools.FACE_LEFT = [
  82471. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82472. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82473. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82474. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82475. ];
  82476. PanoramaToCubeMapTools.FACE_DOWN = [
  82477. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82478. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82479. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82480. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82481. ];
  82482. PanoramaToCubeMapTools.FACE_UP = [
  82483. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82484. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82485. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82486. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82487. ];
  82488. return PanoramaToCubeMapTools;
  82489. }());
  82490. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82491. })(BABYLON || (BABYLON = {}));
  82492. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82493. var BABYLON;
  82494. (function (BABYLON) {
  82495. ;
  82496. /**
  82497. * This groups tools to convert HDR texture to native colors array.
  82498. */
  82499. var HDRTools = /** @class */ (function () {
  82500. function HDRTools() {
  82501. }
  82502. HDRTools.Ldexp = function (mantissa, exponent) {
  82503. if (exponent > 1023) {
  82504. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82505. }
  82506. if (exponent < -1074) {
  82507. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82508. }
  82509. return mantissa * Math.pow(2, exponent);
  82510. };
  82511. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82512. if (exponent > 0) { /*nonzero pixel*/
  82513. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82514. float32array[index + 0] = red * exponent;
  82515. float32array[index + 1] = green * exponent;
  82516. float32array[index + 2] = blue * exponent;
  82517. }
  82518. else {
  82519. float32array[index + 0] = 0;
  82520. float32array[index + 1] = 0;
  82521. float32array[index + 2] = 0;
  82522. }
  82523. };
  82524. HDRTools.readStringLine = function (uint8array, startIndex) {
  82525. var line = "";
  82526. var character = "";
  82527. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82528. character = String.fromCharCode(uint8array[i]);
  82529. if (character == "\n") {
  82530. break;
  82531. }
  82532. line += character;
  82533. }
  82534. return line;
  82535. };
  82536. /**
  82537. * Reads header information from an RGBE texture stored in a native array.
  82538. * More information on this format are available here:
  82539. * https://en.wikipedia.org/wiki/RGBE_image_format
  82540. *
  82541. * @param uint8array The binary file stored in native array.
  82542. * @return The header information.
  82543. */
  82544. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82545. var height = 0;
  82546. var width = 0;
  82547. var line = this.readStringLine(uint8array, 0);
  82548. if (line[0] != '#' || line[1] != '?') {
  82549. throw "Bad HDR Format.";
  82550. }
  82551. var endOfHeader = false;
  82552. var findFormat = false;
  82553. var lineIndex = 0;
  82554. do {
  82555. lineIndex += (line.length + 1);
  82556. line = this.readStringLine(uint8array, lineIndex);
  82557. if (line == "FORMAT=32-bit_rle_rgbe") {
  82558. findFormat = true;
  82559. }
  82560. else if (line.length == 0) {
  82561. endOfHeader = true;
  82562. }
  82563. } while (!endOfHeader);
  82564. if (!findFormat) {
  82565. throw "HDR Bad header format, unsupported FORMAT";
  82566. }
  82567. lineIndex += (line.length + 1);
  82568. line = this.readStringLine(uint8array, lineIndex);
  82569. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82570. var match = sizeRegexp.exec(line);
  82571. // TODO. Support +Y and -X if needed.
  82572. if (!match || match.length < 3) {
  82573. throw "HDR Bad header format, no size";
  82574. }
  82575. width = parseInt(match[2]);
  82576. height = parseInt(match[1]);
  82577. if (width < 8 || width > 0x7fff) {
  82578. throw "HDR Bad header format, unsupported size";
  82579. }
  82580. lineIndex += (line.length + 1);
  82581. return {
  82582. height: height,
  82583. width: width,
  82584. dataPosition: lineIndex
  82585. };
  82586. };
  82587. /**
  82588. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82589. * This RGBE texture needs to store the information as a panorama.
  82590. *
  82591. * More information on this format are available here:
  82592. * https://en.wikipedia.org/wiki/RGBE_image_format
  82593. *
  82594. * @param buffer The binary file stored in an array buffer.
  82595. * @param size The expected size of the extracted cubemap.
  82596. * @return The Cube Map information.
  82597. */
  82598. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82599. var uint8array = new Uint8Array(buffer);
  82600. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82601. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82602. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82603. return cubeMapData;
  82604. };
  82605. /**
  82606. * Returns the pixels data extracted from an RGBE texture.
  82607. * This pixels will be stored left to right up to down in the R G B order in one array.
  82608. *
  82609. * More information on this format are available here:
  82610. * https://en.wikipedia.org/wiki/RGBE_image_format
  82611. *
  82612. * @param uint8array The binary file stored in an array buffer.
  82613. * @param hdrInfo The header information of the file.
  82614. * @return The pixels data in RGB right to left up to down order.
  82615. */
  82616. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82617. // Keep for multi format supports.
  82618. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82619. };
  82620. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82621. var num_scanlines = hdrInfo.height;
  82622. var scanline_width = hdrInfo.width;
  82623. var a, b, c, d, count;
  82624. var dataIndex = hdrInfo.dataPosition;
  82625. var index = 0, endIndex = 0, i = 0;
  82626. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82627. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82628. // 3 channels of 4 bytes per pixel in float.
  82629. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82630. var resultArray = new Float32Array(resultBuffer);
  82631. // read in each successive scanline
  82632. while (num_scanlines > 0) {
  82633. a = uint8array[dataIndex++];
  82634. b = uint8array[dataIndex++];
  82635. c = uint8array[dataIndex++];
  82636. d = uint8array[dataIndex++];
  82637. if (a != 2 || b != 2 || (c & 0x80)) {
  82638. // this file is not run length encoded
  82639. throw "HDR Bad header format, not RLE";
  82640. }
  82641. if (((c << 8) | d) != scanline_width) {
  82642. throw "HDR Bad header format, wrong scan line width";
  82643. }
  82644. index = 0;
  82645. // read each of the four channels for the scanline into the buffer
  82646. for (i = 0; i < 4; i++) {
  82647. endIndex = (i + 1) * scanline_width;
  82648. while (index < endIndex) {
  82649. a = uint8array[dataIndex++];
  82650. b = uint8array[dataIndex++];
  82651. if (a > 128) {
  82652. // a run of the same value
  82653. count = a - 128;
  82654. if ((count == 0) || (count > endIndex - index)) {
  82655. throw "HDR Bad Format, bad scanline data (run)";
  82656. }
  82657. while (count-- > 0) {
  82658. scanLineArray[index++] = b;
  82659. }
  82660. }
  82661. else {
  82662. // a non-run
  82663. count = a;
  82664. if ((count == 0) || (count > endIndex - index)) {
  82665. throw "HDR Bad Format, bad scanline data (non-run)";
  82666. }
  82667. scanLineArray[index++] = b;
  82668. if (--count > 0) {
  82669. for (var j = 0; j < count; j++) {
  82670. scanLineArray[index++] = uint8array[dataIndex++];
  82671. }
  82672. }
  82673. }
  82674. }
  82675. }
  82676. // now convert data from buffer into floats
  82677. for (i = 0; i < scanline_width; i++) {
  82678. a = scanLineArray[i];
  82679. b = scanLineArray[i + scanline_width];
  82680. c = scanLineArray[i + 2 * scanline_width];
  82681. d = scanLineArray[i + 3 * scanline_width];
  82682. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82683. }
  82684. num_scanlines--;
  82685. }
  82686. return resultArray;
  82687. };
  82688. return HDRTools;
  82689. }());
  82690. BABYLON.HDRTools = HDRTools;
  82691. })(BABYLON || (BABYLON = {}));
  82692. //# sourceMappingURL=babylon.hdr.js.map
  82693. var BABYLON;
  82694. (function (BABYLON) {
  82695. /**
  82696. * Sets of helpers addressing the serialization and deserialization of environment texture
  82697. * stored in a BabylonJS env file.
  82698. * Those files are usually stored as .env files.
  82699. */
  82700. var EnvironmentTextureTools = /** @class */ (function () {
  82701. function EnvironmentTextureTools() {
  82702. }
  82703. /**
  82704. * Gets the environment info from an env file.
  82705. * @param data The array buffer containing the .env bytes.
  82706. * @returns the environment file info (the json header) if successfully parsed.
  82707. */
  82708. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82709. var dataView = new DataView(data);
  82710. var pos = 0;
  82711. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82712. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82713. BABYLON.Tools.Error('Not a babylon environment map');
  82714. return null;
  82715. }
  82716. }
  82717. // Read json manifest - collect characters up to null terminator
  82718. var manifestString = '';
  82719. var charCode = 0x00;
  82720. while ((charCode = dataView.getUint8(pos++))) {
  82721. manifestString += String.fromCharCode(charCode);
  82722. }
  82723. var manifest = JSON.parse(manifestString);
  82724. if (manifest.specular) {
  82725. // Extend the header with the position of the payload.
  82726. manifest.specular.specularDataPosition = pos;
  82727. }
  82728. return manifest;
  82729. };
  82730. /**
  82731. * Creates an environment texture from a loaded cube texture.
  82732. * @param texture defines the cube texture to convert in env file
  82733. * @return a promise containing the environment data if succesfull.
  82734. */
  82735. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82736. var _this = this;
  82737. var internalTexture = texture.getInternalTexture();
  82738. if (!internalTexture) {
  82739. return Promise.reject("The cube texture is invalid.");
  82740. }
  82741. if (!texture._prefiltered) {
  82742. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82743. }
  82744. var engine = internalTexture.getEngine();
  82745. if (engine && engine.premultipliedAlpha) {
  82746. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82747. }
  82748. var canvas = engine.getRenderingCanvas();
  82749. if (!canvas) {
  82750. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82751. }
  82752. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82753. if (!engine.getCaps().textureFloatRender) {
  82754. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82755. if (!engine.getCaps().textureHalfFloatRender) {
  82756. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82757. }
  82758. }
  82759. var cubeWidth = internalTexture.width;
  82760. var hostingScene = new BABYLON.Scene(engine);
  82761. var specularTextures = {};
  82762. var promises = [];
  82763. // Read and collect all mipmaps data from the cube.
  82764. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82765. mipmapsCount = Math.round(mipmapsCount);
  82766. var _loop_1 = function (i) {
  82767. var faceWidth = Math.pow(2, mipmapsCount - i);
  82768. var _loop_2 = function (face) {
  82769. var data = texture.readPixels(face, i);
  82770. // Creates a temp texture with the face data.
  82771. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82772. // And rgbdEncode them.
  82773. var promise = new Promise(function (resolve, reject) {
  82774. 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);
  82775. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82776. rgbdPostProcess.onApply = function (effect) {
  82777. effect._bindTexture("textureSampler", tempTexture);
  82778. };
  82779. // As the process needs to happen on the main canvas, keep track of the current size
  82780. var currentW = engine.getRenderWidth();
  82781. var currentH = engine.getRenderHeight();
  82782. // Set the desired size for the texture
  82783. engine.setSize(faceWidth, faceWidth);
  82784. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82785. // Reading datas from WebGL
  82786. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82787. var fileReader = new FileReader();
  82788. fileReader.onload = function (event) {
  82789. var arrayBuffer = event.target.result;
  82790. specularTextures[i * 6 + face] = arrayBuffer;
  82791. resolve();
  82792. };
  82793. fileReader.readAsArrayBuffer(blob);
  82794. });
  82795. // Reapply the previous canvas size
  82796. engine.setSize(currentW, currentH);
  82797. });
  82798. });
  82799. promises.push(promise);
  82800. };
  82801. // All faces of the cube.
  82802. for (var face = 0; face < 6; face++) {
  82803. _loop_2(face);
  82804. }
  82805. };
  82806. for (var i = 0; i <= mipmapsCount; i++) {
  82807. _loop_1(i);
  82808. }
  82809. // Once all the textures haves been collected as RGBD stored in PNGs
  82810. return Promise.all(promises).then(function () {
  82811. // We can delete the hosting scene keeping track of all the creation objects
  82812. hostingScene.dispose();
  82813. // Creates the json header for the env texture
  82814. var info = {
  82815. version: 1,
  82816. width: cubeWidth,
  82817. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82818. specular: {
  82819. mipmaps: []
  82820. }
  82821. };
  82822. // Sets the specular image data information
  82823. var position = 0;
  82824. for (var i = 0; i <= mipmapsCount; i++) {
  82825. for (var face = 0; face < 6; face++) {
  82826. var byteLength = specularTextures[i * 6 + face].byteLength;
  82827. info.specular.mipmaps.push({
  82828. length: byteLength,
  82829. position: position
  82830. });
  82831. position += byteLength;
  82832. }
  82833. }
  82834. // Encode the JSON as an array buffer
  82835. var infoString = JSON.stringify(info);
  82836. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82837. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82838. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82839. infoView[i] = infoString.charCodeAt(i);
  82840. }
  82841. // Ends up with a null terminator for easier parsing
  82842. infoView[infoString.length] = 0x00;
  82843. // Computes the final required size and creates the storage
  82844. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82845. var finalBuffer = new ArrayBuffer(totalSize);
  82846. var finalBufferView = new Uint8Array(finalBuffer);
  82847. var dataView = new DataView(finalBuffer);
  82848. // Copy the magic bytes identifying the file in
  82849. var pos = 0;
  82850. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82851. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82852. }
  82853. // Add the json info
  82854. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82855. pos += infoBuffer.byteLength;
  82856. // Finally inserts the texture data
  82857. for (var i = 0; i <= mipmapsCount; i++) {
  82858. for (var face = 0; face < 6; face++) {
  82859. var dataBuffer = specularTextures[i * 6 + face];
  82860. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82861. pos += dataBuffer.byteLength;
  82862. }
  82863. }
  82864. // Voila
  82865. return finalBuffer;
  82866. });
  82867. };
  82868. /**
  82869. * Creates a JSON representation of the spherical data.
  82870. * @param texture defines the texture containing the polynomials
  82871. * @return the JSON representation of the spherical info
  82872. */
  82873. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82874. var polynmials = texture.sphericalPolynomial;
  82875. if (polynmials == null) {
  82876. return null;
  82877. }
  82878. return {
  82879. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82880. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82881. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82882. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82883. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82884. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82885. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82886. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82887. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82888. };
  82889. };
  82890. /**
  82891. * Uploads the texture info contained in the env file to the GPU.
  82892. * @param texture defines the internal texture to upload to
  82893. * @param arrayBuffer defines the buffer cotaining the data to load
  82894. * @param info defines the texture info retrieved through the GetEnvInfo method
  82895. * @returns a promise
  82896. */
  82897. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  82898. if (info.version !== 1) {
  82899. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82900. }
  82901. var specularInfo = info.specular;
  82902. if (!specularInfo) {
  82903. // Nothing else parsed so far
  82904. return Promise.resolve();
  82905. }
  82906. // Double checks the enclosed info
  82907. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82908. mipmapsCount = Math.round(mipmapsCount) + 1;
  82909. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82910. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82911. }
  82912. var imageData = new Array(mipmapsCount);
  82913. for (var i = 0; i < mipmapsCount; i++) {
  82914. imageData[i] = new Array(6);
  82915. for (var face = 0; face < 6; face++) {
  82916. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  82917. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  82918. }
  82919. }
  82920. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  82921. };
  82922. /**
  82923. * Uploads the levels of image data to the GPU.
  82924. * @param texture defines the internal texture to upload to
  82925. * @param imageData defines the array buffer views of image data [mipmap][face]
  82926. * @returns a promise
  82927. */
  82928. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  82929. var mipmapsCount = imageData.length;
  82930. // Gets everything ready.
  82931. var engine = texture.getEngine();
  82932. var expandTexture = false;
  82933. var generateNonLODTextures = false;
  82934. var rgbdPostProcess = null;
  82935. var cubeRtt = null;
  82936. var lodTextures = null;
  82937. var caps = engine.getCaps();
  82938. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82939. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82940. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82941. // Add extra process if texture lod is not supported
  82942. if (!caps.textureLOD) {
  82943. expandTexture = false;
  82944. generateNonLODTextures = true;
  82945. lodTextures = {};
  82946. }
  82947. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82948. else if (engine.webGLVersion < 2) {
  82949. expandTexture = false;
  82950. }
  82951. // If half float available we can uncompress the texture
  82952. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82953. expandTexture = true;
  82954. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82955. }
  82956. // If full float available we can uncompress the texture
  82957. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82958. expandTexture = true;
  82959. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82960. }
  82961. // Expand the texture if possible
  82962. if (expandTexture) {
  82963. // Simply run through the decode PP
  82964. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82965. texture._isRGBD = false;
  82966. texture.invertY = false;
  82967. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82968. generateDepthBuffer: false,
  82969. generateMipMaps: true,
  82970. generateStencilBuffer: false,
  82971. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82972. type: texture.type,
  82973. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82974. });
  82975. }
  82976. else {
  82977. texture._isRGBD = true;
  82978. texture.invertY = true;
  82979. // In case of missing support, applies the same patch than DDS files.
  82980. if (generateNonLODTextures) {
  82981. var mipSlices = 3;
  82982. var scale = texture._lodGenerationScale;
  82983. var offset = texture._lodGenerationOffset;
  82984. for (var i = 0; i < mipSlices; i++) {
  82985. //compute LOD from even spacing in smoothness (matching shader calculation)
  82986. var smoothness = i / (mipSlices - 1);
  82987. var roughness = 1 - smoothness;
  82988. var minLODIndex = offset; // roughness = 0
  82989. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  82990. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82991. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82992. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82993. glTextureFromLod.isCube = true;
  82994. glTextureFromLod.invertY = true;
  82995. glTextureFromLod.generateMipMaps = false;
  82996. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82997. // Wrap in a base texture for easy binding.
  82998. var lodTexture = new BABYLON.BaseTexture(null);
  82999. lodTexture.isCube = true;
  83000. lodTexture._texture = glTextureFromLod;
  83001. lodTextures[mipmapIndex] = lodTexture;
  83002. switch (i) {
  83003. case 0:
  83004. texture._lodTextureLow = lodTexture;
  83005. break;
  83006. case 1:
  83007. texture._lodTextureMid = lodTexture;
  83008. break;
  83009. case 2:
  83010. texture._lodTextureHigh = lodTexture;
  83011. break;
  83012. }
  83013. }
  83014. }
  83015. }
  83016. var promises = [];
  83017. var _loop_3 = function (i) {
  83018. var _loop_4 = function (face) {
  83019. // Constructs an image element from image data
  83020. var bytes = imageData[i][face];
  83021. var blob = new Blob([bytes], { type: 'image/png' });
  83022. var url = URL.createObjectURL(blob);
  83023. var image = new Image();
  83024. image.src = url;
  83025. // Enqueue promise to upload to the texture.
  83026. var promise = new Promise(function (resolve, reject) {
  83027. image.onload = function () {
  83028. if (expandTexture) {
  83029. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  83030. reject(message);
  83031. }, image);
  83032. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  83033. // Uncompress the data to a RTT
  83034. rgbdPostProcess.onApply = function (effect) {
  83035. effect._bindTexture("textureSampler", tempTexture_1);
  83036. effect.setFloat2("scale", 1, 1);
  83037. };
  83038. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  83039. // Cleanup
  83040. engine.restoreDefaultFramebuffer();
  83041. tempTexture_1.dispose();
  83042. window.URL.revokeObjectURL(url);
  83043. resolve();
  83044. });
  83045. }
  83046. else {
  83047. engine._uploadImageToTexture(texture, face, i, image);
  83048. // Upload the face to the none lod texture support
  83049. if (generateNonLODTextures) {
  83050. var lodTexture = lodTextures[i];
  83051. if (lodTexture) {
  83052. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  83053. }
  83054. }
  83055. resolve();
  83056. }
  83057. };
  83058. image.onerror = function (error) {
  83059. reject(error);
  83060. };
  83061. });
  83062. promises.push(promise);
  83063. };
  83064. // All faces
  83065. for (var face = 0; face < 6; face++) {
  83066. _loop_4(face);
  83067. }
  83068. };
  83069. // All mipmaps
  83070. for (var i = 0; i < mipmapsCount; i++) {
  83071. _loop_3(i);
  83072. }
  83073. // Once all done, finishes the cleanup and return
  83074. return Promise.all(promises).then(function () {
  83075. // Relase temp RTT.
  83076. if (cubeRtt) {
  83077. engine._releaseFramebufferObjects(cubeRtt);
  83078. cubeRtt._swapAndDie(texture);
  83079. }
  83080. // Relase temp Post Process.
  83081. if (rgbdPostProcess) {
  83082. rgbdPostProcess.dispose();
  83083. }
  83084. // Flag internal texture as ready in case they are in use.
  83085. if (generateNonLODTextures) {
  83086. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  83087. texture._lodTextureHigh._texture.isReady = true;
  83088. }
  83089. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  83090. texture._lodTextureMid._texture.isReady = true;
  83091. }
  83092. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  83093. texture._lodTextureLow._texture.isReady = true;
  83094. }
  83095. }
  83096. });
  83097. };
  83098. /**
  83099. * Uploads spherical polynomials information to the texture.
  83100. * @param texture defines the texture we are trying to upload the information to
  83101. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  83102. */
  83103. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  83104. if (info.version !== 1) {
  83105. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  83106. }
  83107. var irradianceInfo = info.irradiance;
  83108. if (!irradianceInfo) {
  83109. return;
  83110. }
  83111. var sp = new BABYLON.SphericalPolynomial();
  83112. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  83113. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  83114. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  83115. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  83116. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  83117. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  83118. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  83119. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  83120. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  83121. texture._sphericalPolynomial = sp;
  83122. };
  83123. /**
  83124. * Magic number identifying the env file.
  83125. */
  83126. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  83127. return EnvironmentTextureTools;
  83128. }());
  83129. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  83130. })(BABYLON || (BABYLON = {}));
  83131. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  83132. var BABYLON;
  83133. (function (BABYLON) {
  83134. /**
  83135. * This represents a texture coming from an HDR input.
  83136. *
  83137. * The only supported format is currently panorama picture stored in RGBE format.
  83138. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83139. */
  83140. var HDRCubeTexture = /** @class */ (function (_super) {
  83141. __extends(HDRCubeTexture, _super);
  83142. /**
  83143. * Instantiates an HDRTexture from the following parameters.
  83144. *
  83145. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83146. * @param scene The scene the texture will be used in
  83147. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83148. * @param noMipmap Forces to not generate the mipmap if true
  83149. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83150. * @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)
  83151. * @param reserved Reserved flag for internal use.
  83152. */
  83153. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83154. if (noMipmap === void 0) { noMipmap = false; }
  83155. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83156. if (gammaSpace === void 0) { gammaSpace = false; }
  83157. if (reserved === void 0) { reserved = false; }
  83158. if (onLoad === void 0) { onLoad = null; }
  83159. if (onError === void 0) { onError = null; }
  83160. var _this = _super.call(this, scene) || this;
  83161. _this._generateHarmonics = true;
  83162. _this._onLoad = null;
  83163. _this._onError = null;
  83164. /**
  83165. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83166. */
  83167. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83168. _this._isBlocking = true;
  83169. _this._rotationY = 0;
  83170. /**
  83171. * Gets or sets the center of the bounding box associated with the cube texture
  83172. * It must define where the camera used to render the texture was set
  83173. */
  83174. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83175. if (!url) {
  83176. return _this;
  83177. }
  83178. _this.name = url;
  83179. _this.url = url;
  83180. _this.hasAlpha = false;
  83181. _this.isCube = true;
  83182. _this._textureMatrix = BABYLON.Matrix.Identity();
  83183. _this._onLoad = onLoad;
  83184. _this._onError = onError;
  83185. _this.gammaSpace = gammaSpace;
  83186. _this._noMipmap = noMipmap;
  83187. _this._size = size;
  83188. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83189. if (!_this._texture) {
  83190. if (!scene.useDelayedTextureLoading) {
  83191. _this.loadTexture();
  83192. }
  83193. else {
  83194. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83195. }
  83196. }
  83197. return _this;
  83198. }
  83199. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83200. /**
  83201. * Gets wether or not the texture is blocking during loading.
  83202. */
  83203. get: function () {
  83204. return this._isBlocking;
  83205. },
  83206. /**
  83207. * Sets wether or not the texture is blocking during loading.
  83208. */
  83209. set: function (value) {
  83210. this._isBlocking = value;
  83211. },
  83212. enumerable: true,
  83213. configurable: true
  83214. });
  83215. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83216. /**
  83217. * Gets texture matrix rotation angle around Y axis radians.
  83218. */
  83219. get: function () {
  83220. return this._rotationY;
  83221. },
  83222. /**
  83223. * Sets texture matrix rotation angle around Y axis in radians.
  83224. */
  83225. set: function (value) {
  83226. this._rotationY = value;
  83227. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83228. },
  83229. enumerable: true,
  83230. configurable: true
  83231. });
  83232. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83233. get: function () {
  83234. return this._boundingBoxSize;
  83235. },
  83236. /**
  83237. * Gets or sets the size of the bounding box associated with the cube texture
  83238. * When defined, the cubemap will switch to local mode
  83239. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83240. * @example https://www.babylonjs-playground.com/#RNASML
  83241. */
  83242. set: function (value) {
  83243. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83244. return;
  83245. }
  83246. this._boundingBoxSize = value;
  83247. var scene = this.getScene();
  83248. if (scene) {
  83249. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83250. }
  83251. },
  83252. enumerable: true,
  83253. configurable: true
  83254. });
  83255. /**
  83256. * Occurs when the file is raw .hdr file.
  83257. */
  83258. HDRCubeTexture.prototype.loadTexture = function () {
  83259. var _this = this;
  83260. var callback = function (buffer) {
  83261. _this.lodGenerationOffset = 0.0;
  83262. _this.lodGenerationScale = 0.8;
  83263. var scene = _this.getScene();
  83264. if (!scene) {
  83265. return null;
  83266. }
  83267. // Extract the raw linear data.
  83268. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83269. // Generate harmonics if needed.
  83270. if (_this._generateHarmonics) {
  83271. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83272. _this.sphericalPolynomial = sphericalPolynomial;
  83273. }
  83274. var results = [];
  83275. var byteArray = null;
  83276. // Push each faces.
  83277. for (var j = 0; j < 6; j++) {
  83278. // Create uintarray fallback.
  83279. if (!scene.getEngine().getCaps().textureFloat) {
  83280. // 3 channels of 1 bytes per pixel in bytes.
  83281. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83282. byteArray = new Uint8Array(byteBuffer);
  83283. }
  83284. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83285. // If special cases.
  83286. if (_this.gammaSpace || byteArray) {
  83287. for (var i = 0; i < _this._size * _this._size; i++) {
  83288. // Put in gamma space if requested.
  83289. if (_this.gammaSpace) {
  83290. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83291. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83292. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83293. }
  83294. // Convert to int texture for fallback.
  83295. if (byteArray) {
  83296. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83297. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83298. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83299. // May use luminance instead if the result is not accurate.
  83300. var max = Math.max(Math.max(r, g), b);
  83301. if (max > 255) {
  83302. var scale = 255 / max;
  83303. r *= scale;
  83304. g *= scale;
  83305. b *= scale;
  83306. }
  83307. byteArray[(i * 3) + 0] = r;
  83308. byteArray[(i * 3) + 1] = g;
  83309. byteArray[(i * 3) + 2] = b;
  83310. }
  83311. }
  83312. }
  83313. if (byteArray) {
  83314. results.push(byteArray);
  83315. }
  83316. else {
  83317. results.push(dataFace);
  83318. }
  83319. }
  83320. return results;
  83321. };
  83322. var scene = this.getScene();
  83323. if (scene) {
  83324. 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);
  83325. }
  83326. };
  83327. HDRCubeTexture.prototype.clone = function () {
  83328. var scene = this.getScene();
  83329. if (!scene) {
  83330. return this;
  83331. }
  83332. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83333. // Base texture
  83334. newTexture.level = this.level;
  83335. newTexture.wrapU = this.wrapU;
  83336. newTexture.wrapV = this.wrapV;
  83337. newTexture.coordinatesIndex = this.coordinatesIndex;
  83338. newTexture.coordinatesMode = this.coordinatesMode;
  83339. return newTexture;
  83340. };
  83341. // Methods
  83342. HDRCubeTexture.prototype.delayLoad = function () {
  83343. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83344. return;
  83345. }
  83346. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83347. this._texture = this._getFromCache(this.url, this._noMipmap);
  83348. if (!this._texture) {
  83349. this.loadTexture();
  83350. }
  83351. };
  83352. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83353. return this._textureMatrix;
  83354. };
  83355. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83356. this._textureMatrix = value;
  83357. };
  83358. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83359. var texture = null;
  83360. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83361. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83362. texture.name = parsedTexture.name;
  83363. texture.hasAlpha = parsedTexture.hasAlpha;
  83364. texture.level = parsedTexture.level;
  83365. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83366. texture.isBlocking = parsedTexture.isBlocking;
  83367. }
  83368. if (texture) {
  83369. if (parsedTexture.boundingBoxPosition) {
  83370. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83371. }
  83372. if (parsedTexture.boundingBoxSize) {
  83373. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83374. }
  83375. if (parsedTexture.rotationY) {
  83376. texture.rotationY = parsedTexture.rotationY;
  83377. }
  83378. }
  83379. return texture;
  83380. };
  83381. HDRCubeTexture.prototype.serialize = function () {
  83382. if (!this.name) {
  83383. return null;
  83384. }
  83385. var serializationObject = {};
  83386. serializationObject.name = this.name;
  83387. serializationObject.hasAlpha = this.hasAlpha;
  83388. serializationObject.isCube = true;
  83389. serializationObject.level = this.level;
  83390. serializationObject.size = this._size;
  83391. serializationObject.coordinatesMode = this.coordinatesMode;
  83392. serializationObject.useInGammaSpace = this.gammaSpace;
  83393. serializationObject.generateHarmonics = this._generateHarmonics;
  83394. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83395. serializationObject.noMipmap = this._noMipmap;
  83396. serializationObject.isBlocking = this._isBlocking;
  83397. serializationObject.rotationY = this._rotationY;
  83398. return serializationObject;
  83399. };
  83400. HDRCubeTexture._facesMapping = [
  83401. "right",
  83402. "left",
  83403. "up",
  83404. "down",
  83405. "front",
  83406. "back"
  83407. ];
  83408. return HDRCubeTexture;
  83409. }(BABYLON.BaseTexture));
  83410. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83411. })(BABYLON || (BABYLON = {}));
  83412. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83413. var BABYLON;
  83414. (function (BABYLON) {
  83415. var IndexedVector2 = /** @class */ (function (_super) {
  83416. __extends(IndexedVector2, _super);
  83417. function IndexedVector2(original, index) {
  83418. var _this = _super.call(this, original.x, original.y) || this;
  83419. _this.index = index;
  83420. return _this;
  83421. }
  83422. return IndexedVector2;
  83423. }(BABYLON.Vector2));
  83424. var PolygonPoints = /** @class */ (function () {
  83425. function PolygonPoints() {
  83426. this.elements = new Array();
  83427. }
  83428. PolygonPoints.prototype.add = function (originalPoints) {
  83429. var _this = this;
  83430. var result = new Array();
  83431. originalPoints.forEach(function (point) {
  83432. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83433. var newPoint = new IndexedVector2(point, _this.elements.length);
  83434. result.push(newPoint);
  83435. _this.elements.push(newPoint);
  83436. }
  83437. });
  83438. return result;
  83439. };
  83440. PolygonPoints.prototype.computeBounds = function () {
  83441. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83442. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83443. this.elements.forEach(function (point) {
  83444. // x
  83445. if (point.x < lmin.x) {
  83446. lmin.x = point.x;
  83447. }
  83448. else if (point.x > lmax.x) {
  83449. lmax.x = point.x;
  83450. }
  83451. // y
  83452. if (point.y < lmin.y) {
  83453. lmin.y = point.y;
  83454. }
  83455. else if (point.y > lmax.y) {
  83456. lmax.y = point.y;
  83457. }
  83458. });
  83459. return {
  83460. min: lmin,
  83461. max: lmax,
  83462. width: lmax.x - lmin.x,
  83463. height: lmax.y - lmin.y
  83464. };
  83465. };
  83466. return PolygonPoints;
  83467. }());
  83468. var Polygon = /** @class */ (function () {
  83469. function Polygon() {
  83470. }
  83471. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83472. return [
  83473. new BABYLON.Vector2(xmin, ymin),
  83474. new BABYLON.Vector2(xmax, ymin),
  83475. new BABYLON.Vector2(xmax, ymax),
  83476. new BABYLON.Vector2(xmin, ymax)
  83477. ];
  83478. };
  83479. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83480. if (cx === void 0) { cx = 0; }
  83481. if (cy === void 0) { cy = 0; }
  83482. if (numberOfSides === void 0) { numberOfSides = 32; }
  83483. var result = new Array();
  83484. var angle = 0;
  83485. var increment = (Math.PI * 2) / numberOfSides;
  83486. for (var i = 0; i < numberOfSides; i++) {
  83487. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83488. angle -= increment;
  83489. }
  83490. return result;
  83491. };
  83492. Polygon.Parse = function (input) {
  83493. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83494. var i, result = [];
  83495. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83496. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83497. }
  83498. return result;
  83499. };
  83500. Polygon.StartingAt = function (x, y) {
  83501. return BABYLON.Path2.StartingAt(x, y);
  83502. };
  83503. return Polygon;
  83504. }());
  83505. BABYLON.Polygon = Polygon;
  83506. var PolygonMeshBuilder = /** @class */ (function () {
  83507. function PolygonMeshBuilder(name, contours, scene) {
  83508. this._points = new PolygonPoints();
  83509. this._outlinepoints = new PolygonPoints();
  83510. this._holes = new Array();
  83511. this._epoints = new Array();
  83512. this._eholes = new Array();
  83513. this._name = name;
  83514. this._scene = scene;
  83515. var points;
  83516. if (contours instanceof BABYLON.Path2) {
  83517. points = contours.getPoints();
  83518. }
  83519. else {
  83520. points = contours;
  83521. }
  83522. this._addToepoint(points);
  83523. this._points.add(points);
  83524. this._outlinepoints.add(points);
  83525. if (typeof earcut === 'undefined') {
  83526. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83527. }
  83528. }
  83529. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83530. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83531. var p = points_1[_i];
  83532. this._epoints.push(p.x, p.y);
  83533. }
  83534. };
  83535. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83536. this._points.add(hole);
  83537. var holepoints = new PolygonPoints();
  83538. holepoints.add(hole);
  83539. this._holes.push(holepoints);
  83540. this._eholes.push(this._epoints.length / 2);
  83541. this._addToepoint(hole);
  83542. return this;
  83543. };
  83544. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83545. var _this = this;
  83546. if (updatable === void 0) { updatable = false; }
  83547. if (depth === void 0) { depth = 0; }
  83548. var result = new BABYLON.Mesh(this._name, this._scene);
  83549. var normals = new Array();
  83550. var positions = new Array();
  83551. var uvs = new Array();
  83552. var bounds = this._points.computeBounds();
  83553. this._points.elements.forEach(function (p) {
  83554. normals.push(0, 1.0, 0);
  83555. positions.push(p.x, 0, p.y);
  83556. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83557. });
  83558. var indices = new Array();
  83559. var res = earcut(this._epoints, this._eholes, 2);
  83560. for (var i = 0; i < res.length; i++) {
  83561. indices.push(res[i]);
  83562. }
  83563. if (depth > 0) {
  83564. var positionscount = (positions.length / 3); //get the current pointcount
  83565. this._points.elements.forEach(function (p) {
  83566. normals.push(0, -1.0, 0);
  83567. positions.push(p.x, -depth, p.y);
  83568. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83569. });
  83570. var totalCount = indices.length;
  83571. for (var i = 0; i < totalCount; i += 3) {
  83572. var i0 = indices[i + 0];
  83573. var i1 = indices[i + 1];
  83574. var i2 = indices[i + 2];
  83575. indices.push(i2 + positionscount);
  83576. indices.push(i1 + positionscount);
  83577. indices.push(i0 + positionscount);
  83578. }
  83579. //Add the sides
  83580. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83581. this._holes.forEach(function (hole) {
  83582. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83583. });
  83584. }
  83585. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83586. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83587. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83588. result.setIndices(indices);
  83589. return result;
  83590. };
  83591. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83592. var StartIndex = positions.length / 3;
  83593. var ulength = 0;
  83594. for (var i = 0; i < points.elements.length; i++) {
  83595. var p = points.elements[i];
  83596. var p1;
  83597. if ((i + 1) > points.elements.length - 1) {
  83598. p1 = points.elements[0];
  83599. }
  83600. else {
  83601. p1 = points.elements[i + 1];
  83602. }
  83603. positions.push(p.x, 0, p.y);
  83604. positions.push(p.x, -depth, p.y);
  83605. positions.push(p1.x, 0, p1.y);
  83606. positions.push(p1.x, -depth, p1.y);
  83607. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83608. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83609. var v3 = v2.subtract(v1);
  83610. var v4 = new BABYLON.Vector3(0, 1, 0);
  83611. var vn = BABYLON.Vector3.Cross(v3, v4);
  83612. vn = vn.normalize();
  83613. uvs.push(ulength / bounds.width, 0);
  83614. uvs.push(ulength / bounds.width, 1);
  83615. ulength += v3.length();
  83616. uvs.push((ulength / bounds.width), 0);
  83617. uvs.push((ulength / bounds.width), 1);
  83618. if (!flip) {
  83619. normals.push(-vn.x, -vn.y, -vn.z);
  83620. normals.push(-vn.x, -vn.y, -vn.z);
  83621. normals.push(-vn.x, -vn.y, -vn.z);
  83622. normals.push(-vn.x, -vn.y, -vn.z);
  83623. indices.push(StartIndex);
  83624. indices.push(StartIndex + 1);
  83625. indices.push(StartIndex + 2);
  83626. indices.push(StartIndex + 1);
  83627. indices.push(StartIndex + 3);
  83628. indices.push(StartIndex + 2);
  83629. }
  83630. else {
  83631. normals.push(vn.x, vn.y, vn.z);
  83632. normals.push(vn.x, vn.y, vn.z);
  83633. normals.push(vn.x, vn.y, vn.z);
  83634. normals.push(vn.x, vn.y, vn.z);
  83635. indices.push(StartIndex);
  83636. indices.push(StartIndex + 2);
  83637. indices.push(StartIndex + 1);
  83638. indices.push(StartIndex + 1);
  83639. indices.push(StartIndex + 2);
  83640. indices.push(StartIndex + 3);
  83641. }
  83642. StartIndex += 4;
  83643. }
  83644. ;
  83645. };
  83646. return PolygonMeshBuilder;
  83647. }());
  83648. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83649. })(BABYLON || (BABYLON = {}));
  83650. //# sourceMappingURL=babylon.polygonMesh.js.map
  83651. var BABYLON;
  83652. (function (BABYLON) {
  83653. // Unique ID when we import meshes from Babylon to CSG
  83654. var currentCSGMeshId = 0;
  83655. // # class Vertex
  83656. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83657. // one to provide additional features like texture coordinates and vertex
  83658. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83659. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83660. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83661. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83662. // is not used anywhere else.
  83663. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83664. var Vertex = /** @class */ (function () {
  83665. function Vertex(pos, normal, uv) {
  83666. this.pos = pos;
  83667. this.normal = normal;
  83668. this.uv = uv;
  83669. }
  83670. Vertex.prototype.clone = function () {
  83671. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83672. };
  83673. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83674. // orientation of a polygon is flipped.
  83675. Vertex.prototype.flip = function () {
  83676. this.normal = this.normal.scale(-1);
  83677. };
  83678. // Create a new vertex between this vertex and `other` by linearly
  83679. // interpolating all properties using a parameter of `t`. Subclasses should
  83680. // override this to interpolate additional properties.
  83681. Vertex.prototype.interpolate = function (other, t) {
  83682. 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));
  83683. };
  83684. return Vertex;
  83685. }());
  83686. // # class Plane
  83687. // Represents a plane in 3D space.
  83688. var Plane = /** @class */ (function () {
  83689. function Plane(normal, w) {
  83690. this.normal = normal;
  83691. this.w = w;
  83692. }
  83693. Plane.FromPoints = function (a, b, c) {
  83694. var v0 = c.subtract(a);
  83695. var v1 = b.subtract(a);
  83696. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83697. return null;
  83698. }
  83699. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83700. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83701. };
  83702. Plane.prototype.clone = function () {
  83703. return new Plane(this.normal.clone(), this.w);
  83704. };
  83705. Plane.prototype.flip = function () {
  83706. this.normal.scaleInPlace(-1);
  83707. this.w = -this.w;
  83708. };
  83709. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83710. // fragments in the appropriate lists. Coplanar polygons go into either
  83711. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83712. // respect to this plane. Polygons in front or in back of this plane go into
  83713. // either `front` or `back`.
  83714. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83715. var COPLANAR = 0;
  83716. var FRONT = 1;
  83717. var BACK = 2;
  83718. var SPANNING = 3;
  83719. // Classify each point as well as the entire polygon into one of the above
  83720. // four classes.
  83721. var polygonType = 0;
  83722. var types = [];
  83723. var i;
  83724. var t;
  83725. for (i = 0; i < polygon.vertices.length; i++) {
  83726. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83727. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83728. polygonType |= type;
  83729. types.push(type);
  83730. }
  83731. // Put the polygon in the correct list, splitting it when necessary.
  83732. switch (polygonType) {
  83733. case COPLANAR:
  83734. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83735. break;
  83736. case FRONT:
  83737. front.push(polygon);
  83738. break;
  83739. case BACK:
  83740. back.push(polygon);
  83741. break;
  83742. case SPANNING:
  83743. var f = [], b = [];
  83744. for (i = 0; i < polygon.vertices.length; i++) {
  83745. var j = (i + 1) % polygon.vertices.length;
  83746. var ti = types[i], tj = types[j];
  83747. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83748. if (ti !== BACK)
  83749. f.push(vi);
  83750. if (ti !== FRONT)
  83751. b.push(ti !== BACK ? vi.clone() : vi);
  83752. if ((ti | tj) === SPANNING) {
  83753. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83754. var v = vi.interpolate(vj, t);
  83755. f.push(v);
  83756. b.push(v.clone());
  83757. }
  83758. }
  83759. var poly;
  83760. if (f.length >= 3) {
  83761. poly = new Polygon(f, polygon.shared);
  83762. if (poly.plane)
  83763. front.push(poly);
  83764. }
  83765. if (b.length >= 3) {
  83766. poly = new Polygon(b, polygon.shared);
  83767. if (poly.plane)
  83768. back.push(poly);
  83769. }
  83770. break;
  83771. }
  83772. };
  83773. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83774. // point is on the plane.
  83775. Plane.EPSILON = 1e-5;
  83776. return Plane;
  83777. }());
  83778. // # class Polygon
  83779. // Represents a convex polygon. The vertices used to initialize a polygon must
  83780. // be coplanar and form a convex loop.
  83781. //
  83782. // Each convex polygon has a `shared` property, which is shared between all
  83783. // polygons that are clones of each other or were split from the same polygon.
  83784. // This can be used to define per-polygon properties (such as surface color).
  83785. var Polygon = /** @class */ (function () {
  83786. function Polygon(vertices, shared) {
  83787. this.vertices = vertices;
  83788. this.shared = shared;
  83789. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83790. }
  83791. Polygon.prototype.clone = function () {
  83792. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83793. return new Polygon(vertices, this.shared);
  83794. };
  83795. Polygon.prototype.flip = function () {
  83796. this.vertices.reverse().map(function (v) { v.flip(); });
  83797. this.plane.flip();
  83798. };
  83799. return Polygon;
  83800. }());
  83801. // # class Node
  83802. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83803. // by picking a polygon to split along. That polygon (and all other coplanar
  83804. // polygons) are added directly to that node and the other polygons are added to
  83805. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83806. // no distinction between internal and leaf nodes.
  83807. var Node = /** @class */ (function () {
  83808. function Node(polygons) {
  83809. this.plane = null;
  83810. this.front = null;
  83811. this.back = null;
  83812. this.polygons = new Array();
  83813. if (polygons) {
  83814. this.build(polygons);
  83815. }
  83816. }
  83817. Node.prototype.clone = function () {
  83818. var node = new Node();
  83819. node.plane = this.plane && this.plane.clone();
  83820. node.front = this.front && this.front.clone();
  83821. node.back = this.back && this.back.clone();
  83822. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83823. return node;
  83824. };
  83825. // Convert solid space to empty space and empty space to solid space.
  83826. Node.prototype.invert = function () {
  83827. for (var i = 0; i < this.polygons.length; i++) {
  83828. this.polygons[i].flip();
  83829. }
  83830. if (this.plane) {
  83831. this.plane.flip();
  83832. }
  83833. if (this.front) {
  83834. this.front.invert();
  83835. }
  83836. if (this.back) {
  83837. this.back.invert();
  83838. }
  83839. var temp = this.front;
  83840. this.front = this.back;
  83841. this.back = temp;
  83842. };
  83843. // Recursively remove all polygons in `polygons` that are inside this BSP
  83844. // tree.
  83845. Node.prototype.clipPolygons = function (polygons) {
  83846. if (!this.plane)
  83847. return polygons.slice();
  83848. var front = new Array(), back = new Array();
  83849. for (var i = 0; i < polygons.length; i++) {
  83850. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83851. }
  83852. if (this.front) {
  83853. front = this.front.clipPolygons(front);
  83854. }
  83855. if (this.back) {
  83856. back = this.back.clipPolygons(back);
  83857. }
  83858. else {
  83859. back = [];
  83860. }
  83861. return front.concat(back);
  83862. };
  83863. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83864. // `bsp`.
  83865. Node.prototype.clipTo = function (bsp) {
  83866. this.polygons = bsp.clipPolygons(this.polygons);
  83867. if (this.front)
  83868. this.front.clipTo(bsp);
  83869. if (this.back)
  83870. this.back.clipTo(bsp);
  83871. };
  83872. // Return a list of all polygons in this BSP tree.
  83873. Node.prototype.allPolygons = function () {
  83874. var polygons = this.polygons.slice();
  83875. if (this.front)
  83876. polygons = polygons.concat(this.front.allPolygons());
  83877. if (this.back)
  83878. polygons = polygons.concat(this.back.allPolygons());
  83879. return polygons;
  83880. };
  83881. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83882. // new polygons are filtered down to the bottom of the tree and become new
  83883. // nodes there. Each set of polygons is partitioned using the first polygon
  83884. // (no heuristic is used to pick a good split).
  83885. Node.prototype.build = function (polygons) {
  83886. if (!polygons.length)
  83887. return;
  83888. if (!this.plane)
  83889. this.plane = polygons[0].plane.clone();
  83890. var front = new Array(), back = new Array();
  83891. for (var i = 0; i < polygons.length; i++) {
  83892. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83893. }
  83894. if (front.length) {
  83895. if (!this.front)
  83896. this.front = new Node();
  83897. this.front.build(front);
  83898. }
  83899. if (back.length) {
  83900. if (!this.back)
  83901. this.back = new Node();
  83902. this.back.build(back);
  83903. }
  83904. };
  83905. return Node;
  83906. }());
  83907. var CSG = /** @class */ (function () {
  83908. function CSG() {
  83909. this.polygons = new Array();
  83910. }
  83911. // Convert BABYLON.Mesh to BABYLON.CSG
  83912. CSG.FromMesh = function (mesh) {
  83913. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83914. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83915. if (mesh instanceof BABYLON.Mesh) {
  83916. mesh.computeWorldMatrix(true);
  83917. matrix = mesh.getWorldMatrix();
  83918. meshPosition = mesh.position.clone();
  83919. meshRotation = mesh.rotation.clone();
  83920. if (mesh.rotationQuaternion) {
  83921. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83922. }
  83923. meshScaling = mesh.scaling.clone();
  83924. }
  83925. else {
  83926. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83927. }
  83928. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83929. var subMeshes = mesh.subMeshes;
  83930. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83931. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83932. vertices = [];
  83933. for (var j = 0; j < 3; j++) {
  83934. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83935. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83936. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83937. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83938. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83939. vertex = new Vertex(position, normal, uv);
  83940. vertices.push(vertex);
  83941. }
  83942. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83943. // To handle the case of degenerated triangle
  83944. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83945. if (polygon.plane)
  83946. polygons.push(polygon);
  83947. }
  83948. }
  83949. var csg = CSG.FromPolygons(polygons);
  83950. csg.matrix = matrix;
  83951. csg.position = meshPosition;
  83952. csg.rotation = meshRotation;
  83953. csg.scaling = meshScaling;
  83954. csg.rotationQuaternion = meshRotationQuaternion;
  83955. currentCSGMeshId++;
  83956. return csg;
  83957. };
  83958. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83959. CSG.FromPolygons = function (polygons) {
  83960. var csg = new CSG();
  83961. csg.polygons = polygons;
  83962. return csg;
  83963. };
  83964. CSG.prototype.clone = function () {
  83965. var csg = new CSG();
  83966. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83967. csg.copyTransformAttributes(this);
  83968. return csg;
  83969. };
  83970. CSG.prototype.union = function (csg) {
  83971. var a = new Node(this.clone().polygons);
  83972. var b = new Node(csg.clone().polygons);
  83973. a.clipTo(b);
  83974. b.clipTo(a);
  83975. b.invert();
  83976. b.clipTo(a);
  83977. b.invert();
  83978. a.build(b.allPolygons());
  83979. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83980. };
  83981. CSG.prototype.unionInPlace = function (csg) {
  83982. var a = new Node(this.polygons);
  83983. var b = new Node(csg.polygons);
  83984. a.clipTo(b);
  83985. b.clipTo(a);
  83986. b.invert();
  83987. b.clipTo(a);
  83988. b.invert();
  83989. a.build(b.allPolygons());
  83990. this.polygons = a.allPolygons();
  83991. };
  83992. CSG.prototype.subtract = function (csg) {
  83993. var a = new Node(this.clone().polygons);
  83994. var b = new Node(csg.clone().polygons);
  83995. a.invert();
  83996. a.clipTo(b);
  83997. b.clipTo(a);
  83998. b.invert();
  83999. b.clipTo(a);
  84000. b.invert();
  84001. a.build(b.allPolygons());
  84002. a.invert();
  84003. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84004. };
  84005. CSG.prototype.subtractInPlace = function (csg) {
  84006. var a = new Node(this.polygons);
  84007. var b = new Node(csg.polygons);
  84008. a.invert();
  84009. a.clipTo(b);
  84010. b.clipTo(a);
  84011. b.invert();
  84012. b.clipTo(a);
  84013. b.invert();
  84014. a.build(b.allPolygons());
  84015. a.invert();
  84016. this.polygons = a.allPolygons();
  84017. };
  84018. CSG.prototype.intersect = function (csg) {
  84019. var a = new Node(this.clone().polygons);
  84020. var b = new Node(csg.clone().polygons);
  84021. a.invert();
  84022. b.clipTo(a);
  84023. b.invert();
  84024. a.clipTo(b);
  84025. b.clipTo(a);
  84026. a.build(b.allPolygons());
  84027. a.invert();
  84028. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84029. };
  84030. CSG.prototype.intersectInPlace = function (csg) {
  84031. var a = new Node(this.polygons);
  84032. var b = new Node(csg.polygons);
  84033. a.invert();
  84034. b.clipTo(a);
  84035. b.invert();
  84036. a.clipTo(b);
  84037. b.clipTo(a);
  84038. a.build(b.allPolygons());
  84039. a.invert();
  84040. this.polygons = a.allPolygons();
  84041. };
  84042. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84043. // not modified.
  84044. CSG.prototype.inverse = function () {
  84045. var csg = this.clone();
  84046. csg.inverseInPlace();
  84047. return csg;
  84048. };
  84049. CSG.prototype.inverseInPlace = function () {
  84050. this.polygons.map(function (p) { p.flip(); });
  84051. };
  84052. // This is used to keep meshes transformations so they can be restored
  84053. // when we build back a Babylon Mesh
  84054. // NB : All CSG operations are performed in world coordinates
  84055. CSG.prototype.copyTransformAttributes = function (csg) {
  84056. this.matrix = csg.matrix;
  84057. this.position = csg.position;
  84058. this.rotation = csg.rotation;
  84059. this.scaling = csg.scaling;
  84060. this.rotationQuaternion = csg.rotationQuaternion;
  84061. return this;
  84062. };
  84063. // Build Raw mesh from CSG
  84064. // Coordinates here are in world space
  84065. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84066. var matrix = this.matrix.clone();
  84067. matrix.invert();
  84068. 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;
  84069. if (keepSubMeshes) {
  84070. // Sort Polygons, since subMeshes are indices range
  84071. polygons.sort(function (a, b) {
  84072. if (a.shared.meshId === b.shared.meshId) {
  84073. return a.shared.subMeshId - b.shared.subMeshId;
  84074. }
  84075. else {
  84076. return a.shared.meshId - b.shared.meshId;
  84077. }
  84078. });
  84079. }
  84080. for (var i = 0, il = polygons.length; i < il; i++) {
  84081. polygon = polygons[i];
  84082. // Building SubMeshes
  84083. if (!subMesh_dict[polygon.shared.meshId]) {
  84084. subMesh_dict[polygon.shared.meshId] = {};
  84085. }
  84086. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84087. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84088. indexStart: +Infinity,
  84089. indexEnd: -Infinity,
  84090. materialIndex: polygon.shared.materialIndex
  84091. };
  84092. }
  84093. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84094. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84095. polygonIndices[0] = 0;
  84096. polygonIndices[1] = j - 1;
  84097. polygonIndices[2] = j;
  84098. for (var k = 0; k < 3; k++) {
  84099. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84100. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84101. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84102. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84103. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84104. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84105. // Check if 2 points can be merged
  84106. if (!(typeof vertex_idx !== 'undefined' &&
  84107. normals[vertex_idx * 3] === localNormal.x &&
  84108. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84109. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84110. uvs[vertex_idx * 2] === uv.x &&
  84111. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84112. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84113. uvs.push(uv.x, uv.y);
  84114. normals.push(normal.x, normal.y, normal.z);
  84115. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84116. }
  84117. indices.push(vertex_idx);
  84118. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84119. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84120. currentIndex++;
  84121. }
  84122. }
  84123. }
  84124. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84125. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84126. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84127. mesh.setIndices(indices, null);
  84128. if (keepSubMeshes) {
  84129. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84130. var materialIndexOffset = 0, materialMaxIndex;
  84131. mesh.subMeshes = new Array();
  84132. for (var m in subMesh_dict) {
  84133. materialMaxIndex = -1;
  84134. for (var sm in subMesh_dict[m]) {
  84135. subMesh_obj = subMesh_dict[m][sm];
  84136. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84137. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84138. }
  84139. materialIndexOffset += ++materialMaxIndex;
  84140. }
  84141. }
  84142. return mesh;
  84143. };
  84144. // Build Mesh from CSG taking material and transforms into account
  84145. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84146. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84147. mesh.material = material;
  84148. mesh.position.copyFrom(this.position);
  84149. mesh.rotation.copyFrom(this.rotation);
  84150. if (this.rotationQuaternion) {
  84151. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84152. }
  84153. mesh.scaling.copyFrom(this.scaling);
  84154. mesh.computeWorldMatrix(true);
  84155. return mesh;
  84156. };
  84157. return CSG;
  84158. }());
  84159. BABYLON.CSG = CSG;
  84160. })(BABYLON || (BABYLON = {}));
  84161. //# sourceMappingURL=babylon.csg.js.map
  84162. var BABYLON;
  84163. (function (BABYLON) {
  84164. var LensFlare = /** @class */ (function () {
  84165. function LensFlare(size, position, color, imgUrl, system) {
  84166. this.size = size;
  84167. this.position = position;
  84168. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84169. this.color = color || new BABYLON.Color3(1, 1, 1);
  84170. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84171. this._system = system;
  84172. system.lensFlares.push(this);
  84173. }
  84174. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84175. return new LensFlare(size, position, color, imgUrl, system);
  84176. };
  84177. LensFlare.prototype.dispose = function () {
  84178. if (this.texture) {
  84179. this.texture.dispose();
  84180. }
  84181. // Remove from scene
  84182. var index = this._system.lensFlares.indexOf(this);
  84183. this._system.lensFlares.splice(index, 1);
  84184. };
  84185. ;
  84186. return LensFlare;
  84187. }());
  84188. BABYLON.LensFlare = LensFlare;
  84189. })(BABYLON || (BABYLON = {}));
  84190. //# sourceMappingURL=babylon.lensFlare.js.map
  84191. var BABYLON;
  84192. (function (BABYLON) {
  84193. // Adds the parser to the scene parsers.
  84194. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84195. // Lens flares
  84196. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84197. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84198. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84199. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84200. container.lensFlareSystems.push(lf);
  84201. }
  84202. }
  84203. });
  84204. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84205. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84206. if (this.lensFlareSystems[index].name === name) {
  84207. return this.lensFlareSystems[index];
  84208. }
  84209. }
  84210. return null;
  84211. };
  84212. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84213. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84214. if (this.lensFlareSystems[index].id === id) {
  84215. return this.lensFlareSystems[index];
  84216. }
  84217. }
  84218. return null;
  84219. };
  84220. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84221. var index = this.lensFlareSystems.indexOf(toRemove);
  84222. if (index !== -1) {
  84223. this.lensFlareSystems.splice(index, 1);
  84224. }
  84225. return index;
  84226. };
  84227. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84228. this.lensFlareSystems.push(newLensFlareSystem);
  84229. };
  84230. /**
  84231. * Defines the layer scene component responsible to manage any layers
  84232. * in a given scene.
  84233. */
  84234. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84235. /**
  84236. * Creates a new instance of the component for the given scene
  84237. * @param scene Defines the scene to register the component in
  84238. */
  84239. function LensFlareSystemSceneComponent(scene) {
  84240. /**
  84241. * The component name helpfull to identify the component in the list of scene components.
  84242. */
  84243. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84244. this.scene = scene;
  84245. this._lensFlareSystems = scene.lensFlareSystems = new Array();
  84246. }
  84247. /**
  84248. * Registers the component in a given scene
  84249. */
  84250. LensFlareSystemSceneComponent.prototype.register = function () {
  84251. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84252. };
  84253. /**
  84254. * Rebuilds the elements related to this component in case of
  84255. * context lost for instance.
  84256. */
  84257. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84258. // Nothing to do for lens flare
  84259. };
  84260. /**
  84261. * Adds all the element from the container to the scene
  84262. * @param container the container holding the elements
  84263. */
  84264. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84265. var _this = this;
  84266. if (!container.lensFlareSystems) {
  84267. return;
  84268. }
  84269. container.lensFlareSystems.forEach(function (o) {
  84270. _this.scene.addLensFlareSystem(o);
  84271. });
  84272. };
  84273. /**
  84274. * Removes all the elements in the container from the scene
  84275. * @param container contains the elements to remove
  84276. */
  84277. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84278. var _this = this;
  84279. if (!container.lensFlareSystems) {
  84280. return;
  84281. }
  84282. container.lensFlareSystems.forEach(function (o) {
  84283. _this.scene.removeLensFlareSystem(o);
  84284. });
  84285. };
  84286. /**
  84287. * Serializes the component data to the specified json object
  84288. * @param serializationObject The object to serialize to
  84289. */
  84290. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84291. // Lens flares
  84292. serializationObject.lensFlareSystems = [];
  84293. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  84294. var lensFlareSystem = _a[_i];
  84295. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84296. }
  84297. };
  84298. /**
  84299. * Disposes the component and the associated ressources.
  84300. */
  84301. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84302. while (this._lensFlareSystems.length) {
  84303. this._lensFlareSystems[0].dispose();
  84304. }
  84305. };
  84306. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84307. // Lens flares
  84308. if (this.scene.lensFlaresEnabled) {
  84309. BABYLON.Tools.StartPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  84310. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  84311. var lensFlareSystem = _a[_i];
  84312. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84313. lensFlareSystem.render();
  84314. }
  84315. }
  84316. BABYLON.Tools.EndPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  84317. }
  84318. };
  84319. return LensFlareSystemSceneComponent;
  84320. }());
  84321. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84322. })(BABYLON || (BABYLON = {}));
  84323. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84324. var BABYLON;
  84325. (function (BABYLON) {
  84326. var LensFlareSystem = /** @class */ (function () {
  84327. function LensFlareSystem(name, emitter, scene) {
  84328. this.name = name;
  84329. this.lensFlares = new Array();
  84330. this.borderLimit = 300;
  84331. this.viewportBorder = 0;
  84332. this.layerMask = 0x0FFFFFFF;
  84333. this._vertexBuffers = {};
  84334. this._isEnabled = true;
  84335. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84336. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84337. if (!component) {
  84338. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84339. scene._addComponent(component);
  84340. }
  84341. this._emitter = emitter;
  84342. this.id = name;
  84343. scene.lensFlareSystems.push(this);
  84344. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84345. var engine = scene.getEngine();
  84346. // VBO
  84347. var vertices = [];
  84348. vertices.push(1, 1);
  84349. vertices.push(-1, 1);
  84350. vertices.push(-1, -1);
  84351. vertices.push(1, -1);
  84352. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84353. // Indices
  84354. var indices = [];
  84355. indices.push(0);
  84356. indices.push(1);
  84357. indices.push(2);
  84358. indices.push(0);
  84359. indices.push(2);
  84360. indices.push(3);
  84361. this._indexBuffer = engine.createIndexBuffer(indices);
  84362. // Effects
  84363. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84364. }
  84365. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84366. get: function () {
  84367. return this._isEnabled;
  84368. },
  84369. set: function (value) {
  84370. this._isEnabled = value;
  84371. },
  84372. enumerable: true,
  84373. configurable: true
  84374. });
  84375. LensFlareSystem.prototype.getScene = function () {
  84376. return this._scene;
  84377. };
  84378. LensFlareSystem.prototype.getEmitter = function () {
  84379. return this._emitter;
  84380. };
  84381. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84382. this._emitter = newEmitter;
  84383. };
  84384. LensFlareSystem.prototype.getEmitterPosition = function () {
  84385. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84386. };
  84387. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84388. var position = this.getEmitterPosition();
  84389. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84390. this._positionX = position.x;
  84391. this._positionY = position.y;
  84392. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84393. if (this.viewportBorder > 0) {
  84394. globalViewport.x -= this.viewportBorder;
  84395. globalViewport.y -= this.viewportBorder;
  84396. globalViewport.width += this.viewportBorder * 2;
  84397. globalViewport.height += this.viewportBorder * 2;
  84398. position.x += this.viewportBorder;
  84399. position.y += this.viewportBorder;
  84400. this._positionX += this.viewportBorder;
  84401. this._positionY += this.viewportBorder;
  84402. }
  84403. if (position.z > 0) {
  84404. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84405. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84406. return true;
  84407. }
  84408. return true;
  84409. }
  84410. return false;
  84411. };
  84412. LensFlareSystem.prototype._isVisible = function () {
  84413. if (!this._isEnabled || !this._scene.activeCamera) {
  84414. return false;
  84415. }
  84416. var emitterPosition = this.getEmitterPosition();
  84417. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84418. var distance = direction.length();
  84419. direction.normalize();
  84420. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84421. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84422. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84423. };
  84424. LensFlareSystem.prototype.render = function () {
  84425. if (!this._effect.isReady() || !this._scene.activeCamera)
  84426. return false;
  84427. var engine = this._scene.getEngine();
  84428. var viewport = this._scene.activeCamera.viewport;
  84429. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84430. // Position
  84431. if (!this.computeEffectivePosition(globalViewport)) {
  84432. return false;
  84433. }
  84434. // Visibility
  84435. if (!this._isVisible()) {
  84436. return false;
  84437. }
  84438. // Intensity
  84439. var awayX;
  84440. var awayY;
  84441. if (this._positionX < this.borderLimit + globalViewport.x) {
  84442. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84443. }
  84444. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84445. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84446. }
  84447. else {
  84448. awayX = 0;
  84449. }
  84450. if (this._positionY < this.borderLimit + globalViewport.y) {
  84451. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84452. }
  84453. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84454. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84455. }
  84456. else {
  84457. awayY = 0;
  84458. }
  84459. var away = (awayX > awayY) ? awayX : awayY;
  84460. away -= this.viewportBorder;
  84461. if (away > this.borderLimit) {
  84462. away = this.borderLimit;
  84463. }
  84464. var intensity = 1.0 - (away / this.borderLimit);
  84465. if (intensity < 0) {
  84466. return false;
  84467. }
  84468. if (intensity > 1.0) {
  84469. intensity = 1.0;
  84470. }
  84471. if (this.viewportBorder > 0) {
  84472. globalViewport.x += this.viewportBorder;
  84473. globalViewport.y += this.viewportBorder;
  84474. globalViewport.width -= this.viewportBorder * 2;
  84475. globalViewport.height -= this.viewportBorder * 2;
  84476. this._positionX -= this.viewportBorder;
  84477. this._positionY -= this.viewportBorder;
  84478. }
  84479. // Position
  84480. var centerX = globalViewport.x + globalViewport.width / 2;
  84481. var centerY = globalViewport.y + globalViewport.height / 2;
  84482. var distX = centerX - this._positionX;
  84483. var distY = centerY - this._positionY;
  84484. // Effects
  84485. engine.enableEffect(this._effect);
  84486. engine.setState(false);
  84487. engine.setDepthBuffer(false);
  84488. // VBOs
  84489. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84490. // Flares
  84491. for (var index = 0; index < this.lensFlares.length; index++) {
  84492. var flare = this.lensFlares[index];
  84493. engine.setAlphaMode(flare.alphaMode);
  84494. var x = centerX - (distX * flare.position);
  84495. var y = centerY - (distY * flare.position);
  84496. var cw = flare.size;
  84497. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84498. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84499. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84500. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84501. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84502. // Texture
  84503. this._effect.setTexture("textureSampler", flare.texture);
  84504. // Color
  84505. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84506. // Draw order
  84507. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84508. }
  84509. engine.setDepthBuffer(true);
  84510. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84511. return true;
  84512. };
  84513. LensFlareSystem.prototype.dispose = function () {
  84514. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84515. if (vertexBuffer) {
  84516. vertexBuffer.dispose();
  84517. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84518. }
  84519. if (this._indexBuffer) {
  84520. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84521. this._indexBuffer = null;
  84522. }
  84523. while (this.lensFlares.length) {
  84524. this.lensFlares[0].dispose();
  84525. }
  84526. // Remove from scene
  84527. var index = this._scene.lensFlareSystems.indexOf(this);
  84528. this._scene.lensFlareSystems.splice(index, 1);
  84529. };
  84530. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84531. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84532. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84533. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84534. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84535. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84536. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84537. var parsedFlare = parsedLensFlareSystem.flares[index];
  84538. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84539. }
  84540. return lensFlareSystem;
  84541. };
  84542. LensFlareSystem.prototype.serialize = function () {
  84543. var serializationObject = {};
  84544. serializationObject.id = this.id;
  84545. serializationObject.name = this.name;
  84546. serializationObject.emitterId = this.getEmitter().id;
  84547. serializationObject.borderLimit = this.borderLimit;
  84548. serializationObject.flares = [];
  84549. for (var index = 0; index < this.lensFlares.length; index++) {
  84550. var flare = this.lensFlares[index];
  84551. serializationObject.flares.push({
  84552. size: flare.size,
  84553. position: flare.position,
  84554. color: flare.color.asArray(),
  84555. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84556. });
  84557. }
  84558. return serializationObject;
  84559. };
  84560. return LensFlareSystem;
  84561. }());
  84562. BABYLON.LensFlareSystem = LensFlareSystem;
  84563. })(BABYLON || (BABYLON = {}));
  84564. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84565. var BABYLON;
  84566. (function (BABYLON) {
  84567. /**
  84568. * This is a holder class for the physics joint created by the physics plugin.
  84569. * It holds a set of functions to control the underlying joint.
  84570. */
  84571. var PhysicsJoint = /** @class */ (function () {
  84572. function PhysicsJoint(type, jointData) {
  84573. this.type = type;
  84574. this.jointData = jointData;
  84575. jointData.nativeParams = jointData.nativeParams || {};
  84576. }
  84577. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84578. get: function () {
  84579. return this._physicsJoint;
  84580. },
  84581. set: function (newJoint) {
  84582. if (this._physicsJoint) {
  84583. //remove from the wolrd
  84584. }
  84585. this._physicsJoint = newJoint;
  84586. },
  84587. enumerable: true,
  84588. configurable: true
  84589. });
  84590. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84591. set: function (physicsPlugin) {
  84592. this._physicsPlugin = physicsPlugin;
  84593. },
  84594. enumerable: true,
  84595. configurable: true
  84596. });
  84597. /**
  84598. * Execute a function that is physics-plugin specific.
  84599. * @param {Function} func the function that will be executed.
  84600. * It accepts two parameters: the physics world and the physics joint.
  84601. */
  84602. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84603. func(this._physicsPlugin.world, this._physicsJoint);
  84604. };
  84605. //TODO check if the native joints are the same
  84606. //Joint Types
  84607. PhysicsJoint.DistanceJoint = 0;
  84608. PhysicsJoint.HingeJoint = 1;
  84609. PhysicsJoint.BallAndSocketJoint = 2;
  84610. PhysicsJoint.WheelJoint = 3;
  84611. PhysicsJoint.SliderJoint = 4;
  84612. //OIMO
  84613. PhysicsJoint.PrismaticJoint = 5;
  84614. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84615. PhysicsJoint.UniversalJoint = 6;
  84616. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84617. //Cannon
  84618. //Similar to a Ball-Joint. Different in params
  84619. PhysicsJoint.PointToPointJoint = 8;
  84620. //Cannon only at the moment
  84621. PhysicsJoint.SpringJoint = 9;
  84622. PhysicsJoint.LockJoint = 10;
  84623. return PhysicsJoint;
  84624. }());
  84625. BABYLON.PhysicsJoint = PhysicsJoint;
  84626. /**
  84627. * A class representing a physics distance joint.
  84628. */
  84629. var DistanceJoint = /** @class */ (function (_super) {
  84630. __extends(DistanceJoint, _super);
  84631. function DistanceJoint(jointData) {
  84632. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84633. }
  84634. /**
  84635. * Update the predefined distance.
  84636. */
  84637. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84638. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84639. };
  84640. return DistanceJoint;
  84641. }(PhysicsJoint));
  84642. BABYLON.DistanceJoint = DistanceJoint;
  84643. var MotorEnabledJoint = /** @class */ (function (_super) {
  84644. __extends(MotorEnabledJoint, _super);
  84645. function MotorEnabledJoint(type, jointData) {
  84646. return _super.call(this, type, jointData) || this;
  84647. }
  84648. /**
  84649. * Set the motor values.
  84650. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84651. * @param {number} force the force to apply
  84652. * @param {number} maxForce max force for this motor.
  84653. */
  84654. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84655. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84656. };
  84657. /**
  84658. * Set the motor's limits.
  84659. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84660. */
  84661. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84662. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84663. };
  84664. return MotorEnabledJoint;
  84665. }(PhysicsJoint));
  84666. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84667. /**
  84668. * This class represents a single hinge physics joint
  84669. */
  84670. var HingeJoint = /** @class */ (function (_super) {
  84671. __extends(HingeJoint, _super);
  84672. function HingeJoint(jointData) {
  84673. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84674. }
  84675. /**
  84676. * Set the motor values.
  84677. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84678. * @param {number} force the force to apply
  84679. * @param {number} maxForce max force for this motor.
  84680. */
  84681. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84682. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84683. };
  84684. /**
  84685. * Set the motor's limits.
  84686. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84687. */
  84688. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84689. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84690. };
  84691. return HingeJoint;
  84692. }(MotorEnabledJoint));
  84693. BABYLON.HingeJoint = HingeJoint;
  84694. /**
  84695. * This class represents a dual hinge physics joint (same as wheel joint)
  84696. */
  84697. var Hinge2Joint = /** @class */ (function (_super) {
  84698. __extends(Hinge2Joint, _super);
  84699. function Hinge2Joint(jointData) {
  84700. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84701. }
  84702. /**
  84703. * Set the motor values.
  84704. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84705. * @param {number} force the force to apply
  84706. * @param {number} maxForce max force for this motor.
  84707. * @param {motorIndex} the motor's index, 0 or 1.
  84708. */
  84709. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84710. if (motorIndex === void 0) { motorIndex = 0; }
  84711. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84712. };
  84713. /**
  84714. * Set the motor limits.
  84715. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84716. * @param {number} upperLimit the upper limit
  84717. * @param {number} lowerLimit lower limit
  84718. * @param {motorIndex} the motor's index, 0 or 1.
  84719. */
  84720. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84721. if (motorIndex === void 0) { motorIndex = 0; }
  84722. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84723. };
  84724. return Hinge2Joint;
  84725. }(MotorEnabledJoint));
  84726. BABYLON.Hinge2Joint = Hinge2Joint;
  84727. })(BABYLON || (BABYLON = {}));
  84728. //# sourceMappingURL=babylon.physicsJoint.js.map
  84729. var BABYLON;
  84730. (function (BABYLON) {
  84731. var PhysicsImpostor = /** @class */ (function () {
  84732. function PhysicsImpostor(object, type, _options, _scene) {
  84733. if (_options === void 0) { _options = { mass: 0 }; }
  84734. var _this = this;
  84735. this.object = object;
  84736. this.type = type;
  84737. this._options = _options;
  84738. this._scene = _scene;
  84739. this._bodyUpdateRequired = false;
  84740. this._onBeforePhysicsStepCallbacks = new Array();
  84741. this._onAfterPhysicsStepCallbacks = new Array();
  84742. this._onPhysicsCollideCallbacks = [];
  84743. this._deltaPosition = BABYLON.Vector3.Zero();
  84744. this._isDisposed = false;
  84745. //temp variables for parent rotation calculations
  84746. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84747. this._tmpQuat = new BABYLON.Quaternion();
  84748. this._tmpQuat2 = new BABYLON.Quaternion();
  84749. /**
  84750. * this function is executed by the physics engine.
  84751. */
  84752. this.beforeStep = function () {
  84753. if (!_this._physicsEngine) {
  84754. return;
  84755. }
  84756. _this.object.translate(_this._deltaPosition, -1);
  84757. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84758. _this.object.computeWorldMatrix(false);
  84759. if (_this.object.parent && _this.object.rotationQuaternion) {
  84760. _this.getParentsRotation();
  84761. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84762. }
  84763. else {
  84764. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84765. }
  84766. if (!_this._options.disableBidirectionalTransformation) {
  84767. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84768. }
  84769. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84770. func(_this);
  84771. });
  84772. };
  84773. /**
  84774. * this function is executed by the physics engine.
  84775. */
  84776. this.afterStep = function () {
  84777. if (!_this._physicsEngine) {
  84778. return;
  84779. }
  84780. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84781. func(_this);
  84782. });
  84783. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84784. // object has now its world rotation. needs to be converted to local.
  84785. if (_this.object.parent && _this.object.rotationQuaternion) {
  84786. _this.getParentsRotation();
  84787. _this._tmpQuat.conjugateInPlace();
  84788. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84789. }
  84790. // take the position set and make it the absolute position of this object.
  84791. _this.object.setAbsolutePosition(_this.object.position);
  84792. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84793. _this.object.translate(_this._deltaPosition, 1);
  84794. };
  84795. /**
  84796. * Legacy collision detection event support
  84797. */
  84798. this.onCollideEvent = null;
  84799. //event and body object due to cannon's event-based architecture.
  84800. this.onCollide = function (e) {
  84801. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84802. return;
  84803. }
  84804. if (!_this._physicsEngine) {
  84805. return;
  84806. }
  84807. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84808. if (otherImpostor) {
  84809. // Legacy collision detection event support
  84810. if (_this.onCollideEvent) {
  84811. _this.onCollideEvent(_this, otherImpostor);
  84812. }
  84813. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84814. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84815. }).forEach(function (obj) {
  84816. obj.callback(_this, otherImpostor);
  84817. });
  84818. }
  84819. };
  84820. //sanity check!
  84821. if (!this.object) {
  84822. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84823. return;
  84824. }
  84825. //legacy support for old syntax.
  84826. if (!this._scene && object.getScene) {
  84827. this._scene = object.getScene();
  84828. }
  84829. if (!this._scene) {
  84830. return;
  84831. }
  84832. this._physicsEngine = this._scene.getPhysicsEngine();
  84833. if (!this._physicsEngine) {
  84834. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84835. }
  84836. else {
  84837. //set the object's quaternion, if not set
  84838. if (!this.object.rotationQuaternion) {
  84839. if (this.object.rotation) {
  84840. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84841. }
  84842. else {
  84843. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84844. }
  84845. }
  84846. //default options params
  84847. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84848. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84849. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84850. this._joints = [];
  84851. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84852. if (!this.object.parent || this._options.ignoreParent) {
  84853. this._init();
  84854. }
  84855. else if (this.object.parent.physicsImpostor) {
  84856. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84857. }
  84858. }
  84859. }
  84860. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84861. get: function () {
  84862. return this._isDisposed;
  84863. },
  84864. enumerable: true,
  84865. configurable: true
  84866. });
  84867. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84868. get: function () {
  84869. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84870. },
  84871. set: function (value) {
  84872. this.setMass(value);
  84873. },
  84874. enumerable: true,
  84875. configurable: true
  84876. });
  84877. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84878. get: function () {
  84879. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84880. },
  84881. set: function (value) {
  84882. if (!this._physicsEngine) {
  84883. return;
  84884. }
  84885. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84886. },
  84887. enumerable: true,
  84888. configurable: true
  84889. });
  84890. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84891. get: function () {
  84892. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84893. },
  84894. set: function (value) {
  84895. if (!this._physicsEngine) {
  84896. return;
  84897. }
  84898. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84899. },
  84900. enumerable: true,
  84901. configurable: true
  84902. });
  84903. /**
  84904. * This function will completly initialize this impostor.
  84905. * It will create a new body - but only if this mesh has no parent.
  84906. * If it has, this impostor will not be used other than to define the impostor
  84907. * of the child mesh.
  84908. */
  84909. PhysicsImpostor.prototype._init = function () {
  84910. if (!this._physicsEngine) {
  84911. return;
  84912. }
  84913. this._physicsEngine.removeImpostor(this);
  84914. this.physicsBody = null;
  84915. this._parent = this._parent || this._getPhysicsParent();
  84916. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84917. this._physicsEngine.addImpostor(this);
  84918. }
  84919. };
  84920. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84921. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84922. var parentMesh = this.object.parent;
  84923. return parentMesh.physicsImpostor;
  84924. }
  84925. return null;
  84926. };
  84927. /**
  84928. * Should a new body be generated.
  84929. */
  84930. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84931. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84932. };
  84933. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84934. this.forceUpdate();
  84935. };
  84936. /**
  84937. * Force a regeneration of this or the parent's impostor's body.
  84938. * Use under cautious - This will remove all joints already implemented.
  84939. */
  84940. PhysicsImpostor.prototype.forceUpdate = function () {
  84941. this._init();
  84942. if (this.parent && !this._options.ignoreParent) {
  84943. this.parent.forceUpdate();
  84944. }
  84945. };
  84946. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84947. /*public get mesh(): AbstractMesh {
  84948. return this._mesh;
  84949. }*/
  84950. /**
  84951. * Gets the body that holds this impostor. Either its own, or its parent.
  84952. */
  84953. get: function () {
  84954. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84955. },
  84956. /**
  84957. * Set the physics body. Used mainly by the physics engine/plugin
  84958. */
  84959. set: function (physicsBody) {
  84960. if (this._physicsBody && this._physicsEngine) {
  84961. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84962. }
  84963. this._physicsBody = physicsBody;
  84964. this.resetUpdateFlags();
  84965. },
  84966. enumerable: true,
  84967. configurable: true
  84968. });
  84969. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84970. get: function () {
  84971. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84972. },
  84973. set: function (value) {
  84974. this._parent = value;
  84975. },
  84976. enumerable: true,
  84977. configurable: true
  84978. });
  84979. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84980. this._bodyUpdateRequired = false;
  84981. };
  84982. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84983. if (this.object.getBoundingInfo) {
  84984. var q = this.object.rotationQuaternion;
  84985. //reset rotation
  84986. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84987. //calculate the world matrix with no rotation
  84988. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84989. var boundingInfo = this.object.getBoundingInfo();
  84990. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84991. //bring back the rotation
  84992. this.object.rotationQuaternion = q;
  84993. //calculate the world matrix with the new rotation
  84994. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84995. return size;
  84996. }
  84997. else {
  84998. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84999. }
  85000. };
  85001. PhysicsImpostor.prototype.getObjectCenter = function () {
  85002. if (this.object.getBoundingInfo) {
  85003. var boundingInfo = this.object.getBoundingInfo();
  85004. return boundingInfo.boundingBox.centerWorld;
  85005. }
  85006. else {
  85007. return this.object.position;
  85008. }
  85009. };
  85010. /**
  85011. * Get a specific parametes from the options parameter.
  85012. */
  85013. PhysicsImpostor.prototype.getParam = function (paramName) {
  85014. return this._options[paramName];
  85015. };
  85016. /**
  85017. * Sets a specific parameter in the options given to the physics plugin
  85018. */
  85019. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85020. this._options[paramName] = value;
  85021. this._bodyUpdateRequired = true;
  85022. };
  85023. /**
  85024. * Specifically change the body's mass option. Won't recreate the physics body object
  85025. */
  85026. PhysicsImpostor.prototype.setMass = function (mass) {
  85027. if (this.getParam("mass") !== mass) {
  85028. this.setParam("mass", mass);
  85029. }
  85030. if (this._physicsEngine) {
  85031. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85032. }
  85033. };
  85034. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85035. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85036. };
  85037. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85038. if (this._physicsEngine) {
  85039. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85040. }
  85041. };
  85042. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85043. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85044. };
  85045. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85046. if (this._physicsEngine) {
  85047. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85048. }
  85049. };
  85050. /**
  85051. * Execute a function with the physics plugin native code.
  85052. * Provide a function the will have two variables - the world object and the physics body object.
  85053. */
  85054. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85055. if (this._physicsEngine) {
  85056. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85057. }
  85058. };
  85059. /**
  85060. * Register a function that will be executed before the physics world is stepping forward.
  85061. */
  85062. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85063. this._onBeforePhysicsStepCallbacks.push(func);
  85064. };
  85065. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85066. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85067. if (index > -1) {
  85068. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85069. }
  85070. else {
  85071. BABYLON.Tools.Warn("Function to remove was not found");
  85072. }
  85073. };
  85074. /**
  85075. * Register a function that will be executed after the physics step
  85076. */
  85077. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85078. this._onAfterPhysicsStepCallbacks.push(func);
  85079. };
  85080. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85081. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85082. if (index > -1) {
  85083. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85084. }
  85085. else {
  85086. BABYLON.Tools.Warn("Function to remove was not found");
  85087. }
  85088. };
  85089. /**
  85090. * register a function that will be executed when this impostor collides against a different body.
  85091. */
  85092. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85093. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85094. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85095. };
  85096. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85097. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85098. var index = -1;
  85099. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85100. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85101. // chcek the arrays match
  85102. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85103. return collidedAgainstList.indexOf(impostor) > -1;
  85104. });
  85105. if (sameList) {
  85106. index = idx;
  85107. }
  85108. return sameList;
  85109. }
  85110. return false;
  85111. });
  85112. if (found) {
  85113. this._onPhysicsCollideCallbacks.splice(index, 1);
  85114. }
  85115. else {
  85116. BABYLON.Tools.Warn("Function to remove was not found");
  85117. }
  85118. };
  85119. PhysicsImpostor.prototype.getParentsRotation = function () {
  85120. var parent = this.object.parent;
  85121. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85122. while (parent) {
  85123. if (parent.rotationQuaternion) {
  85124. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85125. }
  85126. else {
  85127. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85128. }
  85129. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85130. parent = parent.parent;
  85131. }
  85132. return this._tmpQuat;
  85133. };
  85134. /**
  85135. * Apply a force
  85136. */
  85137. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85138. if (this._physicsEngine) {
  85139. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85140. }
  85141. return this;
  85142. };
  85143. /**
  85144. * Apply an impulse
  85145. */
  85146. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85147. if (this._physicsEngine) {
  85148. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85149. }
  85150. return this;
  85151. };
  85152. /**
  85153. * A help function to create a joint.
  85154. */
  85155. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85156. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85157. this.addJoint(otherImpostor, joint);
  85158. return this;
  85159. };
  85160. /**
  85161. * Add a joint to this impostor with a different impostor.
  85162. */
  85163. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85164. this._joints.push({
  85165. otherImpostor: otherImpostor,
  85166. joint: joint
  85167. });
  85168. if (this._physicsEngine) {
  85169. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85170. }
  85171. return this;
  85172. };
  85173. /**
  85174. * Will keep this body still, in a sleep mode.
  85175. */
  85176. PhysicsImpostor.prototype.sleep = function () {
  85177. if (this._physicsEngine) {
  85178. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85179. }
  85180. return this;
  85181. };
  85182. /**
  85183. * Wake the body up.
  85184. */
  85185. PhysicsImpostor.prototype.wakeUp = function () {
  85186. if (this._physicsEngine) {
  85187. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85188. }
  85189. return this;
  85190. };
  85191. PhysicsImpostor.prototype.clone = function (newObject) {
  85192. if (!newObject)
  85193. return null;
  85194. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85195. };
  85196. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85197. var _this = this;
  85198. //no dispose if no physics engine is available.
  85199. if (!this._physicsEngine) {
  85200. return;
  85201. }
  85202. this._joints.forEach(function (j) {
  85203. if (_this._physicsEngine) {
  85204. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85205. }
  85206. });
  85207. //dispose the physics body
  85208. this._physicsEngine.removeImpostor(this);
  85209. if (this.parent) {
  85210. this.parent.forceUpdate();
  85211. }
  85212. else {
  85213. /*this._object.getChildMeshes().forEach(function(mesh) {
  85214. if (mesh.physicsImpostor) {
  85215. if (disposeChildren) {
  85216. mesh.physicsImpostor.dispose();
  85217. mesh.physicsImpostor = null;
  85218. }
  85219. }
  85220. })*/
  85221. }
  85222. this._isDisposed = true;
  85223. };
  85224. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85225. this._deltaPosition.copyFrom(position);
  85226. };
  85227. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85228. if (!this._deltaRotation) {
  85229. this._deltaRotation = new BABYLON.Quaternion();
  85230. }
  85231. this._deltaRotation.copyFrom(rotation);
  85232. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85233. };
  85234. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85235. if (this._physicsEngine) {
  85236. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85237. }
  85238. return this;
  85239. };
  85240. PhysicsImpostor.prototype.getRadius = function () {
  85241. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85242. };
  85243. /**
  85244. * Sync a bone with this impostor
  85245. * @param bone The bone to sync to the impostor.
  85246. * @param boneMesh The mesh that the bone is influencing.
  85247. * @param jointPivot The pivot of the joint / bone in local space.
  85248. * @param distToJoint Optional distance from the impostor to the joint.
  85249. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85250. */
  85251. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85252. var tempVec = PhysicsImpostor._tmpVecs[0];
  85253. var mesh = this.object;
  85254. if (mesh.rotationQuaternion) {
  85255. if (adjustRotation) {
  85256. var tempQuat = PhysicsImpostor._tmpQuat;
  85257. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85258. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85259. }
  85260. else {
  85261. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85262. }
  85263. }
  85264. tempVec.x = 0;
  85265. tempVec.y = 0;
  85266. tempVec.z = 0;
  85267. if (jointPivot) {
  85268. tempVec.x = jointPivot.x;
  85269. tempVec.y = jointPivot.y;
  85270. tempVec.z = jointPivot.z;
  85271. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85272. if (distToJoint === undefined || distToJoint === null) {
  85273. distToJoint = jointPivot.length();
  85274. }
  85275. tempVec.x *= distToJoint;
  85276. tempVec.y *= distToJoint;
  85277. tempVec.z *= distToJoint;
  85278. }
  85279. if (bone.getParent()) {
  85280. tempVec.addInPlace(mesh.getAbsolutePosition());
  85281. bone.setAbsolutePosition(tempVec, boneMesh);
  85282. }
  85283. else {
  85284. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85285. boneMesh.position.x -= tempVec.x;
  85286. boneMesh.position.y -= tempVec.y;
  85287. boneMesh.position.z -= tempVec.z;
  85288. }
  85289. };
  85290. /**
  85291. * Sync impostor to a bone
  85292. * @param bone The bone that the impostor will be synced to.
  85293. * @param boneMesh The mesh that the bone is influencing.
  85294. * @param jointPivot The pivot of the joint / bone in local space.
  85295. * @param distToJoint Optional distance from the impostor to the joint.
  85296. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85297. * @param boneAxis Optional vector3 axis the bone is aligned with
  85298. */
  85299. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85300. var mesh = this.object;
  85301. if (mesh.rotationQuaternion) {
  85302. if (adjustRotation) {
  85303. var tempQuat = PhysicsImpostor._tmpQuat;
  85304. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85305. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85306. }
  85307. else {
  85308. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85309. }
  85310. }
  85311. var pos = PhysicsImpostor._tmpVecs[0];
  85312. var boneDir = PhysicsImpostor._tmpVecs[1];
  85313. if (!boneAxis) {
  85314. boneAxis = PhysicsImpostor._tmpVecs[2];
  85315. boneAxis.x = 0;
  85316. boneAxis.y = 1;
  85317. boneAxis.z = 0;
  85318. }
  85319. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85320. bone.getAbsolutePositionToRef(boneMesh, pos);
  85321. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85322. distToJoint = jointPivot.length();
  85323. }
  85324. if (distToJoint !== undefined && distToJoint !== null) {
  85325. pos.x += boneDir.x * distToJoint;
  85326. pos.y += boneDir.y * distToJoint;
  85327. pos.z += boneDir.z * distToJoint;
  85328. }
  85329. mesh.setAbsolutePosition(pos);
  85330. };
  85331. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85332. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85333. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85334. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85335. //Impostor types
  85336. PhysicsImpostor.NoImpostor = 0;
  85337. PhysicsImpostor.SphereImpostor = 1;
  85338. PhysicsImpostor.BoxImpostor = 2;
  85339. PhysicsImpostor.PlaneImpostor = 3;
  85340. PhysicsImpostor.MeshImpostor = 4;
  85341. PhysicsImpostor.CylinderImpostor = 7;
  85342. PhysicsImpostor.ParticleImpostor = 8;
  85343. PhysicsImpostor.HeightmapImpostor = 9;
  85344. return PhysicsImpostor;
  85345. }());
  85346. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85347. })(BABYLON || (BABYLON = {}));
  85348. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85349. var BABYLON;
  85350. (function (BABYLON) {
  85351. var PhysicsEngine = /** @class */ (function () {
  85352. function PhysicsEngine(gravity, _physicsPlugin) {
  85353. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85354. this._physicsPlugin = _physicsPlugin;
  85355. //new methods and parameters
  85356. this._impostors = [];
  85357. this._joints = [];
  85358. if (!this._physicsPlugin.isSupported()) {
  85359. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85360. + "Please make sure it is included.");
  85361. }
  85362. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85363. this.setGravity(gravity);
  85364. this.setTimeStep();
  85365. }
  85366. PhysicsEngine.prototype.setGravity = function (gravity) {
  85367. this.gravity = gravity;
  85368. this._physicsPlugin.setGravity(this.gravity);
  85369. };
  85370. /**
  85371. * Set the time step of the physics engine.
  85372. * default is 1/60.
  85373. * To slow it down, enter 1/600 for example.
  85374. * To speed it up, 1/30
  85375. * @param {number} newTimeStep the new timestep to apply to this world.
  85376. */
  85377. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85378. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85379. this._physicsPlugin.setTimeStep(newTimeStep);
  85380. };
  85381. /**
  85382. * Get the time step of the physics engine.
  85383. */
  85384. PhysicsEngine.prototype.getTimeStep = function () {
  85385. return this._physicsPlugin.getTimeStep();
  85386. };
  85387. PhysicsEngine.prototype.dispose = function () {
  85388. this._impostors.forEach(function (impostor) {
  85389. impostor.dispose();
  85390. });
  85391. this._physicsPlugin.dispose();
  85392. };
  85393. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85394. return this._physicsPlugin.name;
  85395. };
  85396. /**
  85397. * Adding a new impostor for the impostor tracking.
  85398. * This will be done by the impostor itself.
  85399. * @param {PhysicsImpostor} impostor the impostor to add
  85400. */
  85401. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85402. impostor.uniqueId = this._impostors.push(impostor);
  85403. //if no parent, generate the body
  85404. if (!impostor.parent) {
  85405. this._physicsPlugin.generatePhysicsBody(impostor);
  85406. }
  85407. };
  85408. /**
  85409. * Remove an impostor from the engine.
  85410. * This impostor and its mesh will not longer be updated by the physics engine.
  85411. * @param {PhysicsImpostor} impostor the impostor to remove
  85412. */
  85413. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85414. var index = this._impostors.indexOf(impostor);
  85415. if (index > -1) {
  85416. var removed = this._impostors.splice(index, 1);
  85417. //Is it needed?
  85418. if (removed.length) {
  85419. //this will also remove it from the world.
  85420. removed[0].physicsBody = null;
  85421. }
  85422. }
  85423. };
  85424. /**
  85425. * Add a joint to the physics engine
  85426. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85427. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85428. * @param {PhysicsJoint} the joint that will connect both impostors.
  85429. */
  85430. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85431. var impostorJoint = {
  85432. mainImpostor: mainImpostor,
  85433. connectedImpostor: connectedImpostor,
  85434. joint: joint
  85435. };
  85436. joint.physicsPlugin = this._physicsPlugin;
  85437. this._joints.push(impostorJoint);
  85438. this._physicsPlugin.generateJoint(impostorJoint);
  85439. };
  85440. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85441. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85442. return (impostorJoint.connectedImpostor === connectedImpostor
  85443. && impostorJoint.joint === joint
  85444. && impostorJoint.mainImpostor === mainImpostor);
  85445. });
  85446. if (matchingJoints.length) {
  85447. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85448. //TODO remove it from the list as well
  85449. }
  85450. };
  85451. /**
  85452. * Called by the scene. no need to call it.
  85453. */
  85454. PhysicsEngine.prototype._step = function (delta) {
  85455. var _this = this;
  85456. //check if any mesh has no body / requires an update
  85457. this._impostors.forEach(function (impostor) {
  85458. if (impostor.isBodyInitRequired()) {
  85459. _this._physicsPlugin.generatePhysicsBody(impostor);
  85460. }
  85461. });
  85462. if (delta > 0.1) {
  85463. delta = 0.1;
  85464. }
  85465. else if (delta <= 0) {
  85466. delta = 1.0 / 60.0;
  85467. }
  85468. this._physicsPlugin.executeStep(delta, this._impostors);
  85469. };
  85470. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85471. return this._physicsPlugin;
  85472. };
  85473. PhysicsEngine.prototype.getImpostors = function () {
  85474. return this._impostors;
  85475. };
  85476. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85477. for (var i = 0; i < this._impostors.length; ++i) {
  85478. if (this._impostors[i].object === object) {
  85479. return this._impostors[i];
  85480. }
  85481. }
  85482. return null;
  85483. };
  85484. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85485. for (var i = 0; i < this._impostors.length; ++i) {
  85486. if (this._impostors[i].physicsBody === body) {
  85487. return this._impostors[i];
  85488. }
  85489. }
  85490. return null;
  85491. };
  85492. // Statics
  85493. PhysicsEngine.Epsilon = 0.001;
  85494. return PhysicsEngine;
  85495. }());
  85496. BABYLON.PhysicsEngine = PhysicsEngine;
  85497. })(BABYLON || (BABYLON = {}));
  85498. //# sourceMappingURL=babylon.physicsEngine.js.map
  85499. var BABYLON;
  85500. (function (BABYLON) {
  85501. var PhysicsHelper = /** @class */ (function () {
  85502. function PhysicsHelper(scene) {
  85503. this._scene = scene;
  85504. this._physicsEngine = this._scene.getPhysicsEngine();
  85505. if (!this._physicsEngine) {
  85506. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85507. }
  85508. }
  85509. /**
  85510. * @param {Vector3} origin the origin of the explosion
  85511. * @param {number} radius the explosion radius
  85512. * @param {number} strength the explosion strength
  85513. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85514. */
  85515. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85516. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85517. if (!this._physicsEngine) {
  85518. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85519. return null;
  85520. }
  85521. var impostors = this._physicsEngine.getImpostors();
  85522. if (impostors.length === 0) {
  85523. return null;
  85524. }
  85525. var event = new PhysicsRadialExplosionEvent(this._scene);
  85526. impostors.forEach(function (impostor) {
  85527. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85528. if (!impostorForceAndContactPoint) {
  85529. return;
  85530. }
  85531. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85532. });
  85533. event.dispose(false);
  85534. return event;
  85535. };
  85536. /**
  85537. * @param {Vector3} origin the origin of the explosion
  85538. * @param {number} radius the explosion radius
  85539. * @param {number} strength the explosion strength
  85540. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85541. */
  85542. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85543. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85544. if (!this._physicsEngine) {
  85545. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85546. return null;
  85547. }
  85548. var impostors = this._physicsEngine.getImpostors();
  85549. if (impostors.length === 0) {
  85550. return null;
  85551. }
  85552. var event = new PhysicsRadialExplosionEvent(this._scene);
  85553. impostors.forEach(function (impostor) {
  85554. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85555. if (!impostorForceAndContactPoint) {
  85556. return;
  85557. }
  85558. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85559. });
  85560. event.dispose(false);
  85561. return event;
  85562. };
  85563. /**
  85564. * @param {Vector3} origin the origin of the explosion
  85565. * @param {number} radius the explosion radius
  85566. * @param {number} strength the explosion strength
  85567. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85568. */
  85569. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85570. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85571. if (!this._physicsEngine) {
  85572. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85573. return null;
  85574. }
  85575. var impostors = this._physicsEngine.getImpostors();
  85576. if (impostors.length === 0) {
  85577. return null;
  85578. }
  85579. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85580. event.dispose(false);
  85581. return event;
  85582. };
  85583. /**
  85584. * @param {Vector3} origin the origin of the updraft
  85585. * @param {number} radius the radius of the updraft
  85586. * @param {number} strength the strength of the updraft
  85587. * @param {number} height the height of the updraft
  85588. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85589. */
  85590. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85591. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85592. if (!this._physicsEngine) {
  85593. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85594. return null;
  85595. }
  85596. if (this._physicsEngine.getImpostors().length === 0) {
  85597. return null;
  85598. }
  85599. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85600. event.dispose(false);
  85601. return event;
  85602. };
  85603. /**
  85604. * @param {Vector3} origin the of the vortex
  85605. * @param {number} radius the radius of the vortex
  85606. * @param {number} strength the strength of the vortex
  85607. * @param {number} height the height of the vortex
  85608. */
  85609. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85610. if (!this._physicsEngine) {
  85611. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85612. return null;
  85613. }
  85614. if (this._physicsEngine.getImpostors().length === 0) {
  85615. return null;
  85616. }
  85617. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85618. event.dispose(false);
  85619. return event;
  85620. };
  85621. return PhysicsHelper;
  85622. }());
  85623. BABYLON.PhysicsHelper = PhysicsHelper;
  85624. /***** Radial explosion *****/
  85625. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85626. function PhysicsRadialExplosionEvent(scene) {
  85627. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85628. this._rays = [];
  85629. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85630. this._scene = scene;
  85631. }
  85632. /**
  85633. * Returns the data related to the radial explosion event (sphere & rays).
  85634. * @returns {PhysicsRadialExplosionEventData}
  85635. */
  85636. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85637. this._dataFetched = true;
  85638. return {
  85639. sphere: this._sphere,
  85640. rays: this._rays,
  85641. };
  85642. };
  85643. /**
  85644. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85645. * @param impostor
  85646. * @param {Vector3} origin the origin of the explosion
  85647. * @param {number} radius the explosion radius
  85648. * @param {number} strength the explosion strength
  85649. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85650. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85651. */
  85652. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85653. if (impostor.mass === 0) {
  85654. return null;
  85655. }
  85656. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85657. return null;
  85658. }
  85659. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85660. return null;
  85661. }
  85662. var impostorObjectCenter = impostor.getObjectCenter();
  85663. var direction = impostorObjectCenter.subtract(origin);
  85664. var ray = new BABYLON.Ray(origin, direction, radius);
  85665. this._rays.push(ray);
  85666. var hit = ray.intersectsMesh(impostor.object);
  85667. var contactPoint = hit.pickedPoint;
  85668. if (!contactPoint) {
  85669. return null;
  85670. }
  85671. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85672. if (distanceFromOrigin > radius) {
  85673. return null;
  85674. }
  85675. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85676. ? strength
  85677. : strength * (1 - (distanceFromOrigin / radius));
  85678. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85679. return { force: force, contactPoint: contactPoint };
  85680. };
  85681. /**
  85682. * Disposes the sphere.
  85683. * @param {bolean} force
  85684. */
  85685. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85686. var _this = this;
  85687. if (force === void 0) { force = true; }
  85688. if (force) {
  85689. this._sphere.dispose();
  85690. }
  85691. else {
  85692. setTimeout(function () {
  85693. if (!_this._dataFetched) {
  85694. _this._sphere.dispose();
  85695. }
  85696. }, 0);
  85697. }
  85698. };
  85699. /*** Helpers ***/
  85700. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85701. if (!this._sphere) {
  85702. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85703. this._sphere.isVisible = false;
  85704. }
  85705. };
  85706. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85707. var impostorObject = impostor.object;
  85708. this._prepareSphere();
  85709. this._sphere.position = origin;
  85710. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85711. this._sphere._updateBoundingInfo();
  85712. this._sphere.computeWorldMatrix(true);
  85713. return this._sphere.intersectsMesh(impostorObject, true);
  85714. };
  85715. return PhysicsRadialExplosionEvent;
  85716. }());
  85717. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85718. /***** Gravitational Field *****/
  85719. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85720. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85721. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85722. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85723. this._physicsHelper = physicsHelper;
  85724. this._scene = scene;
  85725. this._origin = origin;
  85726. this._radius = radius;
  85727. this._strength = strength;
  85728. this._falloff = falloff;
  85729. this._tickCallback = this._tick.bind(this);
  85730. }
  85731. /**
  85732. * Returns the data related to the gravitational field event (sphere).
  85733. * @returns {PhysicsGravitationalFieldEventData}
  85734. */
  85735. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85736. this._dataFetched = true;
  85737. return {
  85738. sphere: this._sphere,
  85739. };
  85740. };
  85741. /**
  85742. * Enables the gravitational field.
  85743. */
  85744. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85745. this._tickCallback.call(this);
  85746. this._scene.registerBeforeRender(this._tickCallback);
  85747. };
  85748. /**
  85749. * Disables the gravitational field.
  85750. */
  85751. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85752. this._scene.unregisterBeforeRender(this._tickCallback);
  85753. };
  85754. /**
  85755. * Disposes the sphere.
  85756. * @param {bolean} force
  85757. */
  85758. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85759. var _this = this;
  85760. if (force === void 0) { force = true; }
  85761. if (force) {
  85762. this._sphere.dispose();
  85763. }
  85764. else {
  85765. setTimeout(function () {
  85766. if (!_this._dataFetched) {
  85767. _this._sphere.dispose();
  85768. }
  85769. }, 0);
  85770. }
  85771. };
  85772. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85773. // Since the params won't change, we fetch the event only once
  85774. if (this._sphere) {
  85775. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85776. }
  85777. else {
  85778. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85779. if (radialExplosionEvent) {
  85780. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85781. }
  85782. }
  85783. };
  85784. return PhysicsGravitationalFieldEvent;
  85785. }());
  85786. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85787. /***** Updraft *****/
  85788. var PhysicsUpdraftEvent = /** @class */ (function () {
  85789. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85790. this._scene = _scene;
  85791. this._origin = _origin;
  85792. this._radius = _radius;
  85793. this._strength = _strength;
  85794. this._height = _height;
  85795. this._updraftMode = _updraftMode;
  85796. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85797. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85798. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85799. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85800. this._physicsEngine = this._scene.getPhysicsEngine();
  85801. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85802. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85803. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85804. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85805. }
  85806. this._tickCallback = this._tick.bind(this);
  85807. }
  85808. /**
  85809. * Returns the data related to the updraft event (cylinder).
  85810. * @returns {PhysicsUpdraftEventData}
  85811. */
  85812. PhysicsUpdraftEvent.prototype.getData = function () {
  85813. this._dataFetched = true;
  85814. return {
  85815. cylinder: this._cylinder,
  85816. };
  85817. };
  85818. /**
  85819. * Enables the updraft.
  85820. */
  85821. PhysicsUpdraftEvent.prototype.enable = function () {
  85822. this._tickCallback.call(this);
  85823. this._scene.registerBeforeRender(this._tickCallback);
  85824. };
  85825. /**
  85826. * Disables the cortex.
  85827. */
  85828. PhysicsUpdraftEvent.prototype.disable = function () {
  85829. this._scene.unregisterBeforeRender(this._tickCallback);
  85830. };
  85831. /**
  85832. * Disposes the sphere.
  85833. * @param {bolean} force
  85834. */
  85835. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85836. var _this = this;
  85837. if (force === void 0) { force = true; }
  85838. if (force) {
  85839. this._cylinder.dispose();
  85840. }
  85841. else {
  85842. setTimeout(function () {
  85843. if (!_this._dataFetched) {
  85844. _this._cylinder.dispose();
  85845. }
  85846. }, 0);
  85847. }
  85848. };
  85849. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85850. if (impostor.mass === 0) {
  85851. return null;
  85852. }
  85853. if (!this._intersectsWithCylinder(impostor)) {
  85854. return null;
  85855. }
  85856. var impostorObjectCenter = impostor.getObjectCenter();
  85857. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85858. var direction = this._originDirection;
  85859. }
  85860. else {
  85861. var direction = impostorObjectCenter.subtract(this._originTop);
  85862. }
  85863. var multiplier = this._strength * -1;
  85864. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85865. return { force: force, contactPoint: impostorObjectCenter };
  85866. };
  85867. PhysicsUpdraftEvent.prototype._tick = function () {
  85868. var _this = this;
  85869. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85870. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85871. if (!impostorForceAndContactPoint) {
  85872. return;
  85873. }
  85874. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85875. });
  85876. };
  85877. /*** Helpers ***/
  85878. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85879. if (!this._cylinder) {
  85880. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85881. height: this._height,
  85882. diameter: this._radius * 2,
  85883. }, this._scene);
  85884. this._cylinder.isVisible = false;
  85885. }
  85886. };
  85887. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85888. var impostorObject = impostor.object;
  85889. this._prepareCylinder();
  85890. this._cylinder.position = this._cylinderPosition;
  85891. return this._cylinder.intersectsMesh(impostorObject, true);
  85892. };
  85893. return PhysicsUpdraftEvent;
  85894. }());
  85895. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85896. /***** Vortex *****/
  85897. var PhysicsVortexEvent = /** @class */ (function () {
  85898. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85899. this._scene = _scene;
  85900. this._origin = _origin;
  85901. this._radius = _radius;
  85902. this._strength = _strength;
  85903. this._height = _height;
  85904. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85905. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85906. this._updraftMultiplier = 0.02;
  85907. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85908. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85909. this._physicsEngine = this._scene.getPhysicsEngine();
  85910. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85911. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85912. this._tickCallback = this._tick.bind(this);
  85913. }
  85914. /**
  85915. * Returns the data related to the vortex event (cylinder).
  85916. * @returns {PhysicsVortexEventData}
  85917. */
  85918. PhysicsVortexEvent.prototype.getData = function () {
  85919. this._dataFetched = true;
  85920. return {
  85921. cylinder: this._cylinder,
  85922. };
  85923. };
  85924. /**
  85925. * Enables the vortex.
  85926. */
  85927. PhysicsVortexEvent.prototype.enable = function () {
  85928. this._tickCallback.call(this);
  85929. this._scene.registerBeforeRender(this._tickCallback);
  85930. };
  85931. /**
  85932. * Disables the cortex.
  85933. */
  85934. PhysicsVortexEvent.prototype.disable = function () {
  85935. this._scene.unregisterBeforeRender(this._tickCallback);
  85936. };
  85937. /**
  85938. * Disposes the sphere.
  85939. * @param {bolean} force
  85940. */
  85941. PhysicsVortexEvent.prototype.dispose = function (force) {
  85942. var _this = this;
  85943. if (force === void 0) { force = true; }
  85944. if (force) {
  85945. this._cylinder.dispose();
  85946. }
  85947. else {
  85948. setTimeout(function () {
  85949. if (!_this._dataFetched) {
  85950. _this._cylinder.dispose();
  85951. }
  85952. }, 0);
  85953. }
  85954. };
  85955. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85956. if (impostor.mass === 0) {
  85957. return null;
  85958. }
  85959. if (!this._intersectsWithCylinder(impostor)) {
  85960. return null;
  85961. }
  85962. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85963. return null;
  85964. }
  85965. var impostorObjectCenter = impostor.getObjectCenter();
  85966. 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)
  85967. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85968. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85969. var hit = ray.intersectsMesh(impostor.object);
  85970. var contactPoint = hit.pickedPoint;
  85971. if (!contactPoint) {
  85972. return null;
  85973. }
  85974. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85975. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85976. var directionToOrigin = contactPoint.normalize();
  85977. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85978. directionToOrigin = directionToOrigin.negate();
  85979. }
  85980. // TODO: find a more physically based solution
  85981. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85982. var forceX = directionToOrigin.x * this._strength / 8;
  85983. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85984. var forceZ = directionToOrigin.z * this._strength / 8;
  85985. }
  85986. else {
  85987. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85988. var forceY = this._originTop.y * this._updraftMultiplier;
  85989. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85990. }
  85991. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85992. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85993. return { force: force, contactPoint: impostorObjectCenter };
  85994. };
  85995. PhysicsVortexEvent.prototype._tick = function () {
  85996. var _this = this;
  85997. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85998. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85999. if (!impostorForceAndContactPoint) {
  86000. return;
  86001. }
  86002. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86003. });
  86004. };
  86005. /*** Helpers ***/
  86006. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86007. if (!this._cylinder) {
  86008. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86009. height: this._height,
  86010. diameter: this._radius * 2,
  86011. }, this._scene);
  86012. this._cylinder.isVisible = false;
  86013. }
  86014. };
  86015. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86016. var impostorObject = impostor.object;
  86017. this._prepareCylinder();
  86018. this._cylinder.position = this._cylinderPosition;
  86019. return this._cylinder.intersectsMesh(impostorObject, true);
  86020. };
  86021. return PhysicsVortexEvent;
  86022. }());
  86023. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86024. /***** Enums *****/
  86025. /**
  86026. * The strenght of the force in correspondence to the distance of the affected object
  86027. */
  86028. var PhysicsRadialImpulseFalloff;
  86029. (function (PhysicsRadialImpulseFalloff) {
  86030. /** Defines that impulse is constant in strength across it's whole radius */
  86031. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86032. /** DEfines that impulse gets weaker if it's further from the origin */
  86033. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86034. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86035. /**
  86036. * The strenght of the force in correspondence to the distance of the affected object
  86037. */
  86038. var PhysicsUpdraftMode;
  86039. (function (PhysicsUpdraftMode) {
  86040. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86041. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86042. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86043. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86044. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86045. })(BABYLON || (BABYLON = {}));
  86046. //# sourceMappingURL=babylon.physicsHelper.js.map
  86047. var BABYLON;
  86048. (function (BABYLON) {
  86049. var CannonJSPlugin = /** @class */ (function () {
  86050. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86051. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86052. if (iterations === void 0) { iterations = 10; }
  86053. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86054. this.name = "CannonJSPlugin";
  86055. this._physicsMaterials = new Array();
  86056. this._fixedTimeStep = 1 / 60;
  86057. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86058. this.BJSCANNON = CANNON;
  86059. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86060. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86061. this._tmpPosition = BABYLON.Vector3.Zero();
  86062. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86063. this._tmpUnityRotation = new BABYLON.Quaternion();
  86064. if (!this.isSupported()) {
  86065. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86066. return;
  86067. }
  86068. this._extendNamespace();
  86069. this.world = new this.BJSCANNON.World();
  86070. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86071. this.world.solver.iterations = iterations;
  86072. }
  86073. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86074. this.world.gravity.copy(gravity);
  86075. };
  86076. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86077. this._fixedTimeStep = timeStep;
  86078. };
  86079. CannonJSPlugin.prototype.getTimeStep = function () {
  86080. return this._fixedTimeStep;
  86081. };
  86082. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86083. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86084. };
  86085. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86086. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86087. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86088. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86089. };
  86090. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86091. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86092. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86093. impostor.physicsBody.applyForce(impulse, worldPoint);
  86094. };
  86095. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86096. //parent-child relationship. Does this impostor has a parent impostor?
  86097. if (impostor.parent) {
  86098. if (impostor.physicsBody) {
  86099. this.removePhysicsBody(impostor);
  86100. //TODO is that needed?
  86101. impostor.forceUpdate();
  86102. }
  86103. return;
  86104. }
  86105. //should a new body be created for this impostor?
  86106. if (impostor.isBodyInitRequired()) {
  86107. var shape = this._createShape(impostor);
  86108. //unregister events, if body is being changed
  86109. var oldBody = impostor.physicsBody;
  86110. if (oldBody) {
  86111. this.removePhysicsBody(impostor);
  86112. }
  86113. //create the body and material
  86114. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86115. var bodyCreationObject = {
  86116. mass: impostor.getParam("mass"),
  86117. material: material
  86118. };
  86119. // A simple extend, in case native options were used.
  86120. var nativeOptions = impostor.getParam("nativeOptions");
  86121. for (var key in nativeOptions) {
  86122. if (nativeOptions.hasOwnProperty(key)) {
  86123. bodyCreationObject[key] = nativeOptions[key];
  86124. }
  86125. }
  86126. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86127. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86128. this.world.addEventListener("preStep", impostor.beforeStep);
  86129. this.world.addEventListener("postStep", impostor.afterStep);
  86130. impostor.physicsBody.addShape(shape);
  86131. this.world.add(impostor.physicsBody);
  86132. //try to keep the body moving in the right direction by taking old properties.
  86133. //Should be tested!
  86134. if (oldBody) {
  86135. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86136. impostor.physicsBody[param].copy(oldBody[param]);
  86137. });
  86138. }
  86139. this._processChildMeshes(impostor);
  86140. }
  86141. //now update the body's transformation
  86142. this._updatePhysicsBodyTransformation(impostor);
  86143. };
  86144. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86145. var _this = this;
  86146. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86147. var currentRotation = mainImpostor.object.rotationQuaternion;
  86148. if (meshChildren.length) {
  86149. var processMesh = function (localPosition, mesh) {
  86150. if (!currentRotation || !mesh.rotationQuaternion) {
  86151. return;
  86152. }
  86153. var childImpostor = mesh.getPhysicsImpostor();
  86154. if (childImpostor) {
  86155. var parent = childImpostor.parent;
  86156. if (parent !== mainImpostor) {
  86157. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86158. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86159. if (childImpostor.physicsBody) {
  86160. _this.removePhysicsBody(childImpostor);
  86161. childImpostor.physicsBody = null;
  86162. }
  86163. childImpostor.parent = mainImpostor;
  86164. childImpostor.resetUpdateFlags();
  86165. 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));
  86166. //Add the mass of the children.
  86167. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86168. }
  86169. }
  86170. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86171. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86172. };
  86173. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86174. }
  86175. };
  86176. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86177. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86178. this.world.removeEventListener("preStep", impostor.beforeStep);
  86179. this.world.removeEventListener("postStep", impostor.afterStep);
  86180. this.world.remove(impostor.physicsBody);
  86181. };
  86182. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86183. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86184. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86185. if (!mainBody || !connectedBody) {
  86186. return;
  86187. }
  86188. var constraint;
  86189. var jointData = impostorJoint.joint.jointData;
  86190. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86191. var constraintData = {
  86192. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86193. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86194. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86195. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86196. maxForce: jointData.nativeParams.maxForce,
  86197. collideConnected: !!jointData.collision
  86198. };
  86199. switch (impostorJoint.joint.type) {
  86200. case BABYLON.PhysicsJoint.HingeJoint:
  86201. case BABYLON.PhysicsJoint.Hinge2Joint:
  86202. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86203. break;
  86204. case BABYLON.PhysicsJoint.DistanceJoint:
  86205. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86206. break;
  86207. case BABYLON.PhysicsJoint.SpringJoint:
  86208. var springData = jointData;
  86209. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86210. restLength: springData.length,
  86211. stiffness: springData.stiffness,
  86212. damping: springData.damping,
  86213. localAnchorA: constraintData.pivotA,
  86214. localAnchorB: constraintData.pivotB
  86215. });
  86216. break;
  86217. case BABYLON.PhysicsJoint.LockJoint:
  86218. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86219. break;
  86220. case BABYLON.PhysicsJoint.PointToPointJoint:
  86221. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86222. default:
  86223. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86224. break;
  86225. }
  86226. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86227. constraint.collideConnected = !!jointData.collision;
  86228. impostorJoint.joint.physicsJoint = constraint;
  86229. //don't add spring as constraint, as it is not one.
  86230. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86231. this.world.addConstraint(constraint);
  86232. }
  86233. else {
  86234. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86235. constraint.applyForce();
  86236. });
  86237. }
  86238. };
  86239. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86240. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86241. };
  86242. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86243. var index;
  86244. var mat;
  86245. for (index = 0; index < this._physicsMaterials.length; index++) {
  86246. mat = this._physicsMaterials[index];
  86247. if (mat.friction === friction && mat.restitution === restitution) {
  86248. return mat;
  86249. }
  86250. }
  86251. var currentMat = new this.BJSCANNON.Material(name);
  86252. currentMat.friction = friction;
  86253. currentMat.restitution = restitution;
  86254. this._physicsMaterials.push(currentMat);
  86255. return currentMat;
  86256. };
  86257. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86258. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86259. };
  86260. CannonJSPlugin.prototype._createShape = function (impostor) {
  86261. var object = impostor.object;
  86262. var returnValue;
  86263. var extendSize = impostor.getObjectExtendSize();
  86264. switch (impostor.type) {
  86265. case BABYLON.PhysicsImpostor.SphereImpostor:
  86266. var radiusX = extendSize.x;
  86267. var radiusY = extendSize.y;
  86268. var radiusZ = extendSize.z;
  86269. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86270. break;
  86271. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86272. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86273. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86274. break;
  86275. case BABYLON.PhysicsImpostor.BoxImpostor:
  86276. var box = extendSize.scale(0.5);
  86277. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86278. break;
  86279. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86280. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86281. returnValue = new this.BJSCANNON.Plane();
  86282. break;
  86283. case BABYLON.PhysicsImpostor.MeshImpostor:
  86284. // should transform the vertex data to world coordinates!!
  86285. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86286. var rawFaces = object.getIndices ? object.getIndices() : [];
  86287. if (!rawVerts)
  86288. return;
  86289. // get only scale! so the object could transform correctly.
  86290. var oldPosition = object.position.clone();
  86291. var oldRotation = object.rotation && object.rotation.clone();
  86292. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86293. object.position.copyFromFloats(0, 0, 0);
  86294. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86295. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86296. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86297. var transform = object.computeWorldMatrix(true);
  86298. // convert rawVerts to object space
  86299. var temp = new Array();
  86300. var index;
  86301. for (index = 0; index < rawVerts.length; index += 3) {
  86302. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86303. }
  86304. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86305. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86306. //now set back the transformation!
  86307. object.position.copyFrom(oldPosition);
  86308. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86309. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86310. break;
  86311. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86312. var oldPosition2 = object.position.clone();
  86313. var oldRotation2 = object.rotation && object.rotation.clone();
  86314. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86315. object.position.copyFromFloats(0, 0, 0);
  86316. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86317. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86318. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86319. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86320. returnValue = this._createHeightmap(object);
  86321. object.position.copyFrom(oldPosition2);
  86322. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86323. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86324. object.computeWorldMatrix(true);
  86325. break;
  86326. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86327. returnValue = new this.BJSCANNON.Particle();
  86328. break;
  86329. }
  86330. return returnValue;
  86331. };
  86332. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86333. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86334. var transform = object.computeWorldMatrix(true);
  86335. // convert rawVerts to object space
  86336. var temp = new Array();
  86337. var index;
  86338. for (index = 0; index < pos.length; index += 3) {
  86339. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86340. }
  86341. pos = temp;
  86342. var matrix = new Array();
  86343. //For now pointDepth will not be used and will be automatically calculated.
  86344. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86345. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86346. var boundingInfo = object.getBoundingInfo();
  86347. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86348. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86349. var elementSize = dim * 2 / arraySize;
  86350. for (var i = 0; i < pos.length; i = i + 3) {
  86351. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86352. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86353. var y = -pos[i + 2] + minY;
  86354. if (!matrix[x]) {
  86355. matrix[x] = [];
  86356. }
  86357. if (!matrix[x][z]) {
  86358. matrix[x][z] = y;
  86359. }
  86360. matrix[x][z] = Math.max(y, matrix[x][z]);
  86361. }
  86362. for (var x = 0; x <= arraySize; ++x) {
  86363. if (!matrix[x]) {
  86364. var loc = 1;
  86365. while (!matrix[(x + loc) % arraySize]) {
  86366. loc++;
  86367. }
  86368. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86369. //console.log("missing x", x);
  86370. }
  86371. for (var z = 0; z <= arraySize; ++z) {
  86372. if (!matrix[x][z]) {
  86373. var loc = 1;
  86374. var newValue;
  86375. while (newValue === undefined) {
  86376. newValue = matrix[x][(z + loc++) % arraySize];
  86377. }
  86378. matrix[x][z] = newValue;
  86379. }
  86380. }
  86381. }
  86382. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86383. elementSize: elementSize
  86384. });
  86385. //For future reference, needed for body transformation
  86386. shape.minY = minY;
  86387. return shape;
  86388. };
  86389. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86390. var object = impostor.object;
  86391. //make sure it is updated...
  86392. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86393. // The delta between the mesh position and the mesh bounding box center
  86394. var bInfo = object.getBoundingInfo();
  86395. if (!bInfo)
  86396. return;
  86397. var center = impostor.getObjectCenter();
  86398. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86399. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86400. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86401. this._tmpPosition.copyFrom(center);
  86402. var quaternion = object.rotationQuaternion;
  86403. if (!quaternion) {
  86404. return;
  86405. }
  86406. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86407. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86408. //-90 DEG in X, precalculated
  86409. quaternion = quaternion.multiply(this._minus90X);
  86410. //Invert! (Precalculated, 90 deg in X)
  86411. //No need to clone. this will never change.
  86412. impostor.setDeltaRotation(this._plus90X);
  86413. }
  86414. //If it is a heightfield, if should be centered.
  86415. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86416. var mesh = object;
  86417. var boundingInfo = mesh.getBoundingInfo();
  86418. //calculate the correct body position:
  86419. var rotationQuaternion = mesh.rotationQuaternion;
  86420. mesh.rotationQuaternion = this._tmpUnityRotation;
  86421. mesh.computeWorldMatrix(true);
  86422. //get original center with no rotation
  86423. var c = center.clone();
  86424. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86425. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86426. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86427. mesh.setPreTransformMatrix(p);
  86428. mesh.computeWorldMatrix(true);
  86429. //calculate the translation
  86430. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86431. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86432. //add it inverted to the delta
  86433. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86434. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86435. //rotation is back
  86436. mesh.rotationQuaternion = rotationQuaternion;
  86437. mesh.setPreTransformMatrix(oldPivot);
  86438. mesh.computeWorldMatrix(true);
  86439. }
  86440. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86441. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86442. //this._tmpPosition.copyFrom(object.position);
  86443. }
  86444. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86445. //Now update the impostor object
  86446. impostor.physicsBody.position.copy(this._tmpPosition);
  86447. impostor.physicsBody.quaternion.copy(quaternion);
  86448. };
  86449. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86450. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86451. if (impostor.object.rotationQuaternion) {
  86452. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86453. }
  86454. };
  86455. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86456. impostor.physicsBody.position.copy(newPosition);
  86457. impostor.physicsBody.quaternion.copy(newRotation);
  86458. };
  86459. CannonJSPlugin.prototype.isSupported = function () {
  86460. return this.BJSCANNON !== undefined;
  86461. };
  86462. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86463. impostor.physicsBody.velocity.copy(velocity);
  86464. };
  86465. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86466. impostor.physicsBody.angularVelocity.copy(velocity);
  86467. };
  86468. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86469. var v = impostor.physicsBody.velocity;
  86470. if (!v) {
  86471. return null;
  86472. }
  86473. return new BABYLON.Vector3(v.x, v.y, v.z);
  86474. };
  86475. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86476. var v = impostor.physicsBody.angularVelocity;
  86477. if (!v) {
  86478. return null;
  86479. }
  86480. return new BABYLON.Vector3(v.x, v.y, v.z);
  86481. };
  86482. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86483. impostor.physicsBody.mass = mass;
  86484. impostor.physicsBody.updateMassProperties();
  86485. };
  86486. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86487. return impostor.physicsBody.mass;
  86488. };
  86489. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86490. return impostor.physicsBody.material.friction;
  86491. };
  86492. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86493. impostor.physicsBody.material.friction = friction;
  86494. };
  86495. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86496. return impostor.physicsBody.material.restitution;
  86497. };
  86498. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86499. impostor.physicsBody.material.restitution = restitution;
  86500. };
  86501. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86502. impostor.physicsBody.sleep();
  86503. };
  86504. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86505. impostor.physicsBody.wakeUp();
  86506. };
  86507. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86508. joint.physicsJoint.distance = maxDistance;
  86509. };
  86510. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86511. // if (!motorIndex) {
  86512. // joint.physicsJoint.enableMotor();
  86513. // }
  86514. // }
  86515. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86516. // if (!motorIndex) {
  86517. // joint.physicsJoint.disableMotor();
  86518. // }
  86519. // }
  86520. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86521. if (!motorIndex) {
  86522. joint.physicsJoint.enableMotor();
  86523. joint.physicsJoint.setMotorSpeed(speed);
  86524. if (maxForce) {
  86525. this.setLimit(joint, maxForce);
  86526. }
  86527. }
  86528. };
  86529. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86530. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86531. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86532. };
  86533. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86534. var body = impostor.physicsBody;
  86535. mesh.position.x = body.position.x;
  86536. mesh.position.y = body.position.y;
  86537. mesh.position.z = body.position.z;
  86538. if (mesh.rotationQuaternion) {
  86539. mesh.rotationQuaternion.x = body.quaternion.x;
  86540. mesh.rotationQuaternion.y = body.quaternion.y;
  86541. mesh.rotationQuaternion.z = body.quaternion.z;
  86542. mesh.rotationQuaternion.w = body.quaternion.w;
  86543. }
  86544. };
  86545. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86546. var shape = impostor.physicsBody.shapes[0];
  86547. return shape.boundingSphereRadius;
  86548. };
  86549. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86550. var shape = impostor.physicsBody.shapes[0];
  86551. result.x = shape.halfExtents.x * 2;
  86552. result.y = shape.halfExtents.y * 2;
  86553. result.z = shape.halfExtents.z * 2;
  86554. };
  86555. CannonJSPlugin.prototype.dispose = function () {
  86556. };
  86557. CannonJSPlugin.prototype._extendNamespace = function () {
  86558. //this will force cannon to execute at least one step when using interpolation
  86559. var step_tmp1 = new this.BJSCANNON.Vec3();
  86560. var Engine = this.BJSCANNON;
  86561. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86562. maxSubSteps = maxSubSteps || 10;
  86563. timeSinceLastCalled = timeSinceLastCalled || 0;
  86564. if (timeSinceLastCalled === 0) {
  86565. this.internalStep(dt);
  86566. this.time += dt;
  86567. }
  86568. else {
  86569. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86570. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86571. var t0 = performance.now();
  86572. for (var i = 0; i !== internalSteps; i++) {
  86573. this.internalStep(dt);
  86574. if (performance.now() - t0 > dt * 1000) {
  86575. break;
  86576. }
  86577. }
  86578. this.time += timeSinceLastCalled;
  86579. var h = this.time % dt;
  86580. var h_div_dt = h / dt;
  86581. var interpvelo = step_tmp1;
  86582. var bodies = this.bodies;
  86583. for (var j = 0; j !== bodies.length; j++) {
  86584. var b = bodies[j];
  86585. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86586. b.position.vsub(b.previousPosition, interpvelo);
  86587. interpvelo.scale(h_div_dt, interpvelo);
  86588. b.position.vadd(interpvelo, b.interpolatedPosition);
  86589. }
  86590. else {
  86591. b.interpolatedPosition.copy(b.position);
  86592. b.interpolatedQuaternion.copy(b.quaternion);
  86593. }
  86594. }
  86595. }
  86596. };
  86597. };
  86598. return CannonJSPlugin;
  86599. }());
  86600. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86601. })(BABYLON || (BABYLON = {}));
  86602. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86603. var BABYLON;
  86604. (function (BABYLON) {
  86605. var OimoJSPlugin = /** @class */ (function () {
  86606. function OimoJSPlugin(iterations) {
  86607. this.name = "OimoJSPlugin";
  86608. this._tmpImpostorsArray = [];
  86609. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86610. this.BJSOIMO = OIMO;
  86611. this.world = new this.BJSOIMO.World({
  86612. iterations: iterations
  86613. });
  86614. this.world.clear();
  86615. }
  86616. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86617. this.world.gravity.copy(gravity);
  86618. };
  86619. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86620. this.world.timeStep = timeStep;
  86621. };
  86622. OimoJSPlugin.prototype.getTimeStep = function () {
  86623. return this.world.timeStep;
  86624. };
  86625. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86626. var _this = this;
  86627. impostors.forEach(function (impostor) {
  86628. impostor.beforeStep();
  86629. });
  86630. this.world.step();
  86631. impostors.forEach(function (impostor) {
  86632. impostor.afterStep();
  86633. //update the ordered impostors array
  86634. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86635. });
  86636. //check for collisions
  86637. var contact = this.world.contacts;
  86638. while (contact !== null) {
  86639. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86640. contact = contact.next;
  86641. continue;
  86642. }
  86643. //is this body colliding with any other? get the impostor
  86644. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86645. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86646. if (!mainImpostor || !collidingImpostor) {
  86647. contact = contact.next;
  86648. continue;
  86649. }
  86650. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86651. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86652. contact = contact.next;
  86653. }
  86654. };
  86655. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86656. var mass = impostor.physicsBody.mass;
  86657. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86658. };
  86659. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86660. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86661. this.applyImpulse(impostor, force, contactPoint);
  86662. };
  86663. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86664. var _this = this;
  86665. //parent-child relationship. Does this impostor has a parent impostor?
  86666. if (impostor.parent) {
  86667. if (impostor.physicsBody) {
  86668. this.removePhysicsBody(impostor);
  86669. //TODO is that needed?
  86670. impostor.forceUpdate();
  86671. }
  86672. return;
  86673. }
  86674. if (impostor.isBodyInitRequired()) {
  86675. var bodyConfig = {
  86676. name: impostor.uniqueId,
  86677. //Oimo must have mass, also for static objects.
  86678. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86679. size: [],
  86680. type: [],
  86681. pos: [],
  86682. posShape: [],
  86683. rot: [],
  86684. rotShape: [],
  86685. move: impostor.getParam("mass") !== 0,
  86686. density: impostor.getParam("mass"),
  86687. friction: impostor.getParam("friction"),
  86688. restitution: impostor.getParam("restitution"),
  86689. //Supporting older versions of Oimo
  86690. world: this.world
  86691. };
  86692. var impostors = [impostor];
  86693. var addToArray = function (parent) {
  86694. if (!parent.getChildMeshes)
  86695. return;
  86696. parent.getChildMeshes().forEach(function (m) {
  86697. if (m.physicsImpostor) {
  86698. impostors.push(m.physicsImpostor);
  86699. //m.physicsImpostor._init();
  86700. }
  86701. });
  86702. };
  86703. addToArray(impostor.object);
  86704. var checkWithEpsilon_1 = function (value) {
  86705. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86706. };
  86707. impostors.forEach(function (i) {
  86708. if (!i.object.rotationQuaternion) {
  86709. return;
  86710. }
  86711. //get the correct bounding box
  86712. var oldQuaternion = i.object.rotationQuaternion;
  86713. var rot = oldQuaternion.toEulerAngles();
  86714. var extendSize = i.getObjectExtendSize();
  86715. var radToDeg = 57.295779513082320876;
  86716. if (i === impostor) {
  86717. var center = impostor.getObjectCenter();
  86718. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86719. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86720. //Can also use Array.prototype.push.apply
  86721. bodyConfig.pos.push(center.x);
  86722. bodyConfig.pos.push(center.y);
  86723. bodyConfig.pos.push(center.z);
  86724. bodyConfig.posShape.push(0, 0, 0);
  86725. //tmp solution
  86726. bodyConfig.rot.push(rot.x * radToDeg);
  86727. bodyConfig.rot.push(rot.y * radToDeg);
  86728. bodyConfig.rot.push(rot.z * radToDeg);
  86729. bodyConfig.rotShape.push(0, 0, 0);
  86730. }
  86731. else {
  86732. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86733. bodyConfig.posShape.push(localPosition.x);
  86734. bodyConfig.posShape.push(localPosition.y);
  86735. bodyConfig.posShape.push(localPosition.z);
  86736. bodyConfig.pos.push(0, 0, 0);
  86737. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86738. bodyConfig.rot.push(0);
  86739. bodyConfig.rot.push(0);
  86740. bodyConfig.rot.push(0);
  86741. bodyConfig.rotShape.push(rot.x * radToDeg);
  86742. bodyConfig.rotShape.push(rot.y * radToDeg);
  86743. bodyConfig.rotShape.push(rot.z * radToDeg);
  86744. }
  86745. // register mesh
  86746. switch (i.type) {
  86747. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86748. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86749. case BABYLON.PhysicsImpostor.SphereImpostor:
  86750. var radiusX = extendSize.x;
  86751. var radiusY = extendSize.y;
  86752. var radiusZ = extendSize.z;
  86753. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86754. bodyConfig.type.push('sphere');
  86755. //due to the way oimo works with compounds, add 3 times
  86756. bodyConfig.size.push(size);
  86757. bodyConfig.size.push(size);
  86758. bodyConfig.size.push(size);
  86759. break;
  86760. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86761. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86762. var sizeY = checkWithEpsilon_1(extendSize.y);
  86763. bodyConfig.type.push('cylinder');
  86764. bodyConfig.size.push(sizeX);
  86765. bodyConfig.size.push(sizeY);
  86766. //due to the way oimo works with compounds, add one more value.
  86767. bodyConfig.size.push(sizeY);
  86768. break;
  86769. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86770. case BABYLON.PhysicsImpostor.BoxImpostor:
  86771. default:
  86772. var sizeX = checkWithEpsilon_1(extendSize.x);
  86773. var sizeY = checkWithEpsilon_1(extendSize.y);
  86774. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86775. bodyConfig.type.push('box');
  86776. //if (i === impostor) {
  86777. bodyConfig.size.push(sizeX);
  86778. bodyConfig.size.push(sizeY);
  86779. bodyConfig.size.push(sizeZ);
  86780. //} else {
  86781. // bodyConfig.size.push(0,0,0);
  86782. //}
  86783. break;
  86784. }
  86785. //actually not needed, but hey...
  86786. i.object.rotationQuaternion = oldQuaternion;
  86787. });
  86788. impostor.physicsBody = this.world.add(bodyConfig);
  86789. }
  86790. else {
  86791. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86792. }
  86793. impostor.setDeltaPosition(this._tmpPositionVector);
  86794. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86795. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86796. };
  86797. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86798. //impostor.physicsBody.dispose();
  86799. //Same as : (older oimo versions)
  86800. this.world.removeRigidBody(impostor.physicsBody);
  86801. };
  86802. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86803. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86804. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86805. if (!mainBody || !connectedBody) {
  86806. return;
  86807. }
  86808. var jointData = impostorJoint.joint.jointData;
  86809. var options = jointData.nativeParams || {};
  86810. var type;
  86811. var nativeJointData = {
  86812. body1: mainBody,
  86813. body2: connectedBody,
  86814. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86815. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86816. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86817. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86818. min: options.min,
  86819. max: options.max,
  86820. collision: options.collision || jointData.collision,
  86821. spring: options.spring,
  86822. //supporting older version of Oimo
  86823. world: this.world
  86824. };
  86825. switch (impostorJoint.joint.type) {
  86826. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86827. type = "jointBall";
  86828. break;
  86829. case BABYLON.PhysicsJoint.SpringJoint:
  86830. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86831. var springData = jointData;
  86832. nativeJointData.min = springData.length || nativeJointData.min;
  86833. //Max should also be set, just make sure it is at least min
  86834. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86835. case BABYLON.PhysicsJoint.DistanceJoint:
  86836. type = "jointDistance";
  86837. nativeJointData.max = jointData.maxDistance;
  86838. break;
  86839. case BABYLON.PhysicsJoint.PrismaticJoint:
  86840. type = "jointPrisme";
  86841. break;
  86842. case BABYLON.PhysicsJoint.SliderJoint:
  86843. type = "jointSlide";
  86844. break;
  86845. case BABYLON.PhysicsJoint.WheelJoint:
  86846. type = "jointWheel";
  86847. break;
  86848. case BABYLON.PhysicsJoint.HingeJoint:
  86849. default:
  86850. type = "jointHinge";
  86851. break;
  86852. }
  86853. nativeJointData.type = type;
  86854. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86855. };
  86856. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86857. //Bug in Oimo prevents us from disposing a joint in the playground
  86858. //joint.joint.physicsJoint.dispose();
  86859. //So we will bruteforce it!
  86860. try {
  86861. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86862. }
  86863. catch (e) {
  86864. BABYLON.Tools.Warn(e);
  86865. }
  86866. };
  86867. OimoJSPlugin.prototype.isSupported = function () {
  86868. return this.BJSOIMO !== undefined;
  86869. };
  86870. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86871. if (!impostor.physicsBody.sleeping) {
  86872. //TODO check that
  86873. /*if (impostor.physicsBody.shapes.next) {
  86874. var parentShape = this._getLastShape(impostor.physicsBody);
  86875. impostor.object.position.copyFrom(parentShape.position);
  86876. console.log(parentShape.position);
  86877. } else {*/
  86878. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86879. //}
  86880. if (impostor.object.rotationQuaternion) {
  86881. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86882. }
  86883. }
  86884. };
  86885. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86886. var body = impostor.physicsBody;
  86887. body.position.copy(newPosition);
  86888. body.orientation.copy(newRotation);
  86889. body.syncShapes();
  86890. body.awake();
  86891. };
  86892. /*private _getLastShape(body: any): any {
  86893. var lastShape = body.shapes;
  86894. while (lastShape.next) {
  86895. lastShape = lastShape.next;
  86896. }
  86897. return lastShape;
  86898. }*/
  86899. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86900. impostor.physicsBody.linearVelocity.copy(velocity);
  86901. };
  86902. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86903. impostor.physicsBody.angularVelocity.copy(velocity);
  86904. };
  86905. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86906. var v = impostor.physicsBody.linearVelocity;
  86907. if (!v) {
  86908. return null;
  86909. }
  86910. return new BABYLON.Vector3(v.x, v.y, v.z);
  86911. };
  86912. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86913. var v = impostor.physicsBody.angularVelocity;
  86914. if (!v) {
  86915. return null;
  86916. }
  86917. return new BABYLON.Vector3(v.x, v.y, v.z);
  86918. };
  86919. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86920. var staticBody = mass === 0;
  86921. //this will actually set the body's density and not its mass.
  86922. //But this is how oimo treats the mass variable.
  86923. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86924. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86925. };
  86926. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86927. return impostor.physicsBody.shapes.density;
  86928. };
  86929. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86930. return impostor.physicsBody.shapes.friction;
  86931. };
  86932. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86933. impostor.physicsBody.shapes.friction = friction;
  86934. };
  86935. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86936. return impostor.physicsBody.shapes.restitution;
  86937. };
  86938. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86939. impostor.physicsBody.shapes.restitution = restitution;
  86940. };
  86941. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86942. impostor.physicsBody.sleep();
  86943. };
  86944. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86945. impostor.physicsBody.awake();
  86946. };
  86947. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86948. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86949. if (minDistance !== void 0) {
  86950. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86951. }
  86952. };
  86953. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86954. //TODO separate rotational and transational motors.
  86955. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86956. if (motor) {
  86957. motor.setMotor(speed, maxForce);
  86958. }
  86959. };
  86960. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86961. //TODO separate rotational and transational motors.
  86962. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86963. if (motor) {
  86964. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86965. }
  86966. };
  86967. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86968. var body = impostor.physicsBody;
  86969. mesh.position.x = body.position.x;
  86970. mesh.position.y = body.position.y;
  86971. mesh.position.z = body.position.z;
  86972. if (mesh.rotationQuaternion) {
  86973. mesh.rotationQuaternion.x = body.orientation.x;
  86974. mesh.rotationQuaternion.y = body.orientation.y;
  86975. mesh.rotationQuaternion.z = body.orientation.z;
  86976. mesh.rotationQuaternion.w = body.orientation.s;
  86977. }
  86978. };
  86979. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86980. return impostor.physicsBody.shapes.radius;
  86981. };
  86982. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86983. var shape = impostor.physicsBody.shapes;
  86984. result.x = shape.halfWidth * 2;
  86985. result.y = shape.halfHeight * 2;
  86986. result.z = shape.halfDepth * 2;
  86987. };
  86988. OimoJSPlugin.prototype.dispose = function () {
  86989. this.world.clear();
  86990. };
  86991. return OimoJSPlugin;
  86992. }());
  86993. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86994. })(BABYLON || (BABYLON = {}));
  86995. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86996. var BABYLON;
  86997. (function (BABYLON) {
  86998. /*
  86999. * Based on jsTGALoader - Javascript loader for TGA file
  87000. * By Vincent Thibault
  87001. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87002. */
  87003. var TGATools = /** @class */ (function () {
  87004. function TGATools() {
  87005. }
  87006. TGATools.GetTGAHeader = function (data) {
  87007. var offset = 0;
  87008. var header = {
  87009. id_length: data[offset++],
  87010. colormap_type: data[offset++],
  87011. image_type: data[offset++],
  87012. colormap_index: data[offset++] | data[offset++] << 8,
  87013. colormap_length: data[offset++] | data[offset++] << 8,
  87014. colormap_size: data[offset++],
  87015. origin: [
  87016. data[offset++] | data[offset++] << 8,
  87017. data[offset++] | data[offset++] << 8
  87018. ],
  87019. width: data[offset++] | data[offset++] << 8,
  87020. height: data[offset++] | data[offset++] << 8,
  87021. pixel_size: data[offset++],
  87022. flags: data[offset++]
  87023. };
  87024. return header;
  87025. };
  87026. TGATools.UploadContent = function (gl, data) {
  87027. // Not enough data to contain header ?
  87028. if (data.length < 19) {
  87029. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87030. return;
  87031. }
  87032. // Read Header
  87033. var offset = 18;
  87034. var header = TGATools.GetTGAHeader(data);
  87035. // Assume it's a valid Targa file.
  87036. if (header.id_length + offset > data.length) {
  87037. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87038. return;
  87039. }
  87040. // Skip not needed data
  87041. offset += header.id_length;
  87042. var use_rle = false;
  87043. var use_pal = false;
  87044. var use_grey = false;
  87045. // Get some informations.
  87046. switch (header.image_type) {
  87047. case TGATools._TYPE_RLE_INDEXED:
  87048. use_rle = true;
  87049. case TGATools._TYPE_INDEXED:
  87050. use_pal = true;
  87051. break;
  87052. case TGATools._TYPE_RLE_RGB:
  87053. use_rle = true;
  87054. case TGATools._TYPE_RGB:
  87055. // use_rgb = true;
  87056. break;
  87057. case TGATools._TYPE_RLE_GREY:
  87058. use_rle = true;
  87059. case TGATools._TYPE_GREY:
  87060. use_grey = true;
  87061. break;
  87062. }
  87063. var pixel_data;
  87064. // var numAlphaBits = header.flags & 0xf;
  87065. var pixel_size = header.pixel_size >> 3;
  87066. var pixel_total = header.width * header.height * pixel_size;
  87067. // Read palettes
  87068. var palettes;
  87069. if (use_pal) {
  87070. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87071. }
  87072. // Read LRE
  87073. if (use_rle) {
  87074. pixel_data = new Uint8Array(pixel_total);
  87075. var c, count, i;
  87076. var localOffset = 0;
  87077. var pixels = new Uint8Array(pixel_size);
  87078. while (offset < pixel_total && localOffset < pixel_total) {
  87079. c = data[offset++];
  87080. count = (c & 0x7f) + 1;
  87081. // RLE pixels
  87082. if (c & 0x80) {
  87083. // Bind pixel tmp array
  87084. for (i = 0; i < pixel_size; ++i) {
  87085. pixels[i] = data[offset++];
  87086. }
  87087. // Copy pixel array
  87088. for (i = 0; i < count; ++i) {
  87089. pixel_data.set(pixels, localOffset + i * pixel_size);
  87090. }
  87091. localOffset += pixel_size * count;
  87092. }
  87093. // Raw pixels
  87094. else {
  87095. count *= pixel_size;
  87096. for (i = 0; i < count; ++i) {
  87097. pixel_data[localOffset + i] = data[offset++];
  87098. }
  87099. localOffset += count;
  87100. }
  87101. }
  87102. }
  87103. // RAW Pixels
  87104. else {
  87105. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87106. }
  87107. // Load to texture
  87108. var x_start, y_start, x_step, y_step, y_end, x_end;
  87109. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87110. default:
  87111. case TGATools._ORIGIN_UL:
  87112. x_start = 0;
  87113. x_step = 1;
  87114. x_end = header.width;
  87115. y_start = 0;
  87116. y_step = 1;
  87117. y_end = header.height;
  87118. break;
  87119. case TGATools._ORIGIN_BL:
  87120. x_start = 0;
  87121. x_step = 1;
  87122. x_end = header.width;
  87123. y_start = header.height - 1;
  87124. y_step = -1;
  87125. y_end = -1;
  87126. break;
  87127. case TGATools._ORIGIN_UR:
  87128. x_start = header.width - 1;
  87129. x_step = -1;
  87130. x_end = -1;
  87131. y_start = 0;
  87132. y_step = 1;
  87133. y_end = header.height;
  87134. break;
  87135. case TGATools._ORIGIN_BR:
  87136. x_start = header.width - 1;
  87137. x_step = -1;
  87138. x_end = -1;
  87139. y_start = header.height - 1;
  87140. y_step = -1;
  87141. y_end = -1;
  87142. break;
  87143. }
  87144. // Load the specify method
  87145. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87146. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87147. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  87148. };
  87149. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87150. var image = pixel_data, colormap = palettes;
  87151. var width = header.width, height = header.height;
  87152. var color, i = 0, x, y;
  87153. var imageData = new Uint8Array(width * height * 4);
  87154. for (y = y_start; y !== y_end; y += y_step) {
  87155. for (x = x_start; x !== x_end; x += x_step, i++) {
  87156. color = image[i];
  87157. imageData[(x + width * y) * 4 + 3] = 255;
  87158. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87159. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87160. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87161. }
  87162. }
  87163. return imageData;
  87164. };
  87165. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87166. var image = pixel_data;
  87167. var width = header.width, height = header.height;
  87168. var color, i = 0, x, y;
  87169. var imageData = new Uint8Array(width * height * 4);
  87170. for (y = y_start; y !== y_end; y += y_step) {
  87171. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87172. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87173. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87174. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87175. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  87176. imageData[(x + width * y) * 4 + 0] = r;
  87177. imageData[(x + width * y) * 4 + 1] = g;
  87178. imageData[(x + width * y) * 4 + 2] = b;
  87179. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  87180. }
  87181. }
  87182. return imageData;
  87183. };
  87184. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87185. var image = pixel_data;
  87186. var width = header.width, height = header.height;
  87187. var i = 0, x, y;
  87188. var imageData = new Uint8Array(width * height * 4);
  87189. for (y = y_start; y !== y_end; y += y_step) {
  87190. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  87191. imageData[(x + width * y) * 4 + 3] = 255;
  87192. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87193. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87194. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87195. }
  87196. }
  87197. return imageData;
  87198. };
  87199. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87200. var image = pixel_data;
  87201. var width = header.width, height = header.height;
  87202. var i = 0, x, y;
  87203. var imageData = new Uint8Array(width * height * 4);
  87204. for (y = y_start; y !== y_end; y += y_step) {
  87205. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  87206. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87207. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87208. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87209. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87210. }
  87211. }
  87212. return imageData;
  87213. };
  87214. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87215. var image = pixel_data;
  87216. var width = header.width, height = header.height;
  87217. var color, i = 0, x, y;
  87218. var imageData = new Uint8Array(width * height * 4);
  87219. for (y = y_start; y !== y_end; y += y_step) {
  87220. for (x = x_start; x !== x_end; x += x_step, i++) {
  87221. color = image[i];
  87222. imageData[(x + width * y) * 4 + 0] = color;
  87223. imageData[(x + width * y) * 4 + 1] = color;
  87224. imageData[(x + width * y) * 4 + 2] = color;
  87225. imageData[(x + width * y) * 4 + 3] = 255;
  87226. }
  87227. }
  87228. return imageData;
  87229. };
  87230. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87231. var image = pixel_data;
  87232. var width = header.width, height = header.height;
  87233. var i = 0, x, y;
  87234. var imageData = new Uint8Array(width * height * 4);
  87235. for (y = y_start; y !== y_end; y += y_step) {
  87236. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87237. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87238. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87239. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87240. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87241. }
  87242. }
  87243. return imageData;
  87244. };
  87245. //private static _TYPE_NO_DATA = 0;
  87246. TGATools._TYPE_INDEXED = 1;
  87247. TGATools._TYPE_RGB = 2;
  87248. TGATools._TYPE_GREY = 3;
  87249. TGATools._TYPE_RLE_INDEXED = 9;
  87250. TGATools._TYPE_RLE_RGB = 10;
  87251. TGATools._TYPE_RLE_GREY = 11;
  87252. TGATools._ORIGIN_MASK = 0x30;
  87253. TGATools._ORIGIN_SHIFT = 0x04;
  87254. TGATools._ORIGIN_BL = 0x00;
  87255. TGATools._ORIGIN_BR = 0x01;
  87256. TGATools._ORIGIN_UL = 0x02;
  87257. TGATools._ORIGIN_UR = 0x03;
  87258. return TGATools;
  87259. }());
  87260. BABYLON.TGATools = TGATools;
  87261. })(BABYLON || (BABYLON = {}));
  87262. //# sourceMappingURL=babylon.tga.js.map
  87263. var BABYLON;
  87264. (function (BABYLON) {
  87265. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87266. // All values and structures referenced from:
  87267. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87268. var DDS_MAGIC = 0x20534444;
  87269. var
  87270. //DDSD_CAPS = 0x1,
  87271. //DDSD_HEIGHT = 0x2,
  87272. //DDSD_WIDTH = 0x4,
  87273. //DDSD_PITCH = 0x8,
  87274. //DDSD_PIXELFORMAT = 0x1000,
  87275. DDSD_MIPMAPCOUNT = 0x20000;
  87276. //DDSD_LINEARSIZE = 0x80000,
  87277. //DDSD_DEPTH = 0x800000;
  87278. // var DDSCAPS_COMPLEX = 0x8,
  87279. // DDSCAPS_MIPMAP = 0x400000,
  87280. // DDSCAPS_TEXTURE = 0x1000;
  87281. var DDSCAPS2_CUBEMAP = 0x200;
  87282. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87283. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87284. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87285. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87286. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87287. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87288. // DDSCAPS2_VOLUME = 0x200000;
  87289. var
  87290. //DDPF_ALPHAPIXELS = 0x1,
  87291. //DDPF_ALPHA = 0x2,
  87292. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87293. //DDPF_YUV = 0x200,
  87294. DDPF_LUMINANCE = 0x20000;
  87295. function FourCCToInt32(value) {
  87296. return value.charCodeAt(0) +
  87297. (value.charCodeAt(1) << 8) +
  87298. (value.charCodeAt(2) << 16) +
  87299. (value.charCodeAt(3) << 24);
  87300. }
  87301. function Int32ToFourCC(value) {
  87302. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87303. }
  87304. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87305. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87306. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87307. var FOURCC_DX10 = FourCCToInt32("DX10");
  87308. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87309. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87310. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87311. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87312. var headerLengthInt = 31; // The header length in 32 bit ints
  87313. // Offsets into the header array
  87314. var off_magic = 0;
  87315. var off_size = 1;
  87316. var off_flags = 2;
  87317. var off_height = 3;
  87318. var off_width = 4;
  87319. var off_mipmapCount = 7;
  87320. var off_pfFlags = 20;
  87321. var off_pfFourCC = 21;
  87322. var off_RGBbpp = 22;
  87323. var off_RMask = 23;
  87324. var off_GMask = 24;
  87325. var off_BMask = 25;
  87326. var off_AMask = 26;
  87327. // var off_caps1 = 27;
  87328. var off_caps2 = 28;
  87329. // var off_caps3 = 29;
  87330. // var off_caps4 = 30;
  87331. var off_dxgiFormat = 32;
  87332. ;
  87333. var DDSTools = /** @class */ (function () {
  87334. function DDSTools() {
  87335. }
  87336. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87337. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87338. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87339. var mipmapCount = 1;
  87340. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87341. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87342. }
  87343. var fourCC = header[off_pfFourCC];
  87344. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87345. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87346. switch (fourCC) {
  87347. case FOURCC_D3DFMT_R16G16B16A16F:
  87348. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87349. break;
  87350. case FOURCC_D3DFMT_R32G32B32A32F:
  87351. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87352. break;
  87353. case FOURCC_DX10:
  87354. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87355. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87356. break;
  87357. }
  87358. }
  87359. return {
  87360. width: header[off_width],
  87361. height: header[off_height],
  87362. mipmapCount: mipmapCount,
  87363. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87364. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87365. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87366. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87367. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87368. dxgiFormat: dxgiFormat,
  87369. textureType: textureType
  87370. };
  87371. };
  87372. DDSTools._ToHalfFloat = function (value) {
  87373. if (!DDSTools._FloatView) {
  87374. DDSTools._FloatView = new Float32Array(1);
  87375. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87376. }
  87377. DDSTools._FloatView[0] = value;
  87378. var x = DDSTools._Int32View[0];
  87379. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87380. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87381. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87382. /* If zero, or denormal, or exponent underflows too much for a denormal
  87383. * half, return signed zero. */
  87384. if (e < 103) {
  87385. return bits;
  87386. }
  87387. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87388. if (e > 142) {
  87389. bits |= 0x7c00;
  87390. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87391. * not Inf, so make sure we set one mantissa bit too. */
  87392. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87393. return bits;
  87394. }
  87395. /* If exponent underflows but not too much, return a denormal */
  87396. if (e < 113) {
  87397. m |= 0x0800;
  87398. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87399. * to 1, which is OK. */
  87400. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87401. return bits;
  87402. }
  87403. bits |= ((e - 112) << 10) | (m >> 1);
  87404. bits += m & 1;
  87405. return bits;
  87406. };
  87407. DDSTools._FromHalfFloat = function (value) {
  87408. var s = (value & 0x8000) >> 15;
  87409. var e = (value & 0x7C00) >> 10;
  87410. var f = value & 0x03FF;
  87411. if (e === 0) {
  87412. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87413. }
  87414. else if (e == 0x1F) {
  87415. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87416. }
  87417. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87418. };
  87419. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87420. var destArray = new Float32Array(dataLength);
  87421. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87422. var index = 0;
  87423. for (var y = 0; y < height; y++) {
  87424. for (var x = 0; x < width; x++) {
  87425. var srcPos = (x + y * width) * 4;
  87426. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87427. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87428. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87429. if (DDSTools.StoreLODInAlphaChannel) {
  87430. destArray[index + 3] = lod;
  87431. }
  87432. else {
  87433. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87434. }
  87435. index += 4;
  87436. }
  87437. }
  87438. return destArray;
  87439. };
  87440. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87441. if (DDSTools.StoreLODInAlphaChannel) {
  87442. var destArray = new Uint16Array(dataLength);
  87443. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87444. var index = 0;
  87445. for (var y = 0; y < height; y++) {
  87446. for (var x = 0; x < width; x++) {
  87447. var srcPos = (x + y * width) * 4;
  87448. destArray[index] = srcData[srcPos];
  87449. destArray[index + 1] = srcData[srcPos + 1];
  87450. destArray[index + 2] = srcData[srcPos + 2];
  87451. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87452. index += 4;
  87453. }
  87454. }
  87455. return destArray;
  87456. }
  87457. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87458. };
  87459. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87460. if (DDSTools.StoreLODInAlphaChannel) {
  87461. var destArray = new Float32Array(dataLength);
  87462. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87463. var index = 0;
  87464. for (var y = 0; y < height; y++) {
  87465. for (var x = 0; x < width; x++) {
  87466. var srcPos = (x + y * width) * 4;
  87467. destArray[index] = srcData[srcPos];
  87468. destArray[index + 1] = srcData[srcPos + 1];
  87469. destArray[index + 2] = srcData[srcPos + 2];
  87470. destArray[index + 3] = lod;
  87471. index += 4;
  87472. }
  87473. }
  87474. return destArray;
  87475. }
  87476. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87477. };
  87478. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87479. var destArray = new Uint8Array(dataLength);
  87480. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87481. var index = 0;
  87482. for (var y = 0; y < height; y++) {
  87483. for (var x = 0; x < width; x++) {
  87484. var srcPos = (x + y * width) * 4;
  87485. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87486. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87487. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87488. if (DDSTools.StoreLODInAlphaChannel) {
  87489. destArray[index + 3] = lod;
  87490. }
  87491. else {
  87492. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87493. }
  87494. index += 4;
  87495. }
  87496. }
  87497. return destArray;
  87498. };
  87499. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87500. var destArray = new Uint8Array(dataLength);
  87501. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87502. var index = 0;
  87503. for (var y = 0; y < height; y++) {
  87504. for (var x = 0; x < width; x++) {
  87505. var srcPos = (x + y * width) * 4;
  87506. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87507. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87508. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87509. if (DDSTools.StoreLODInAlphaChannel) {
  87510. destArray[index + 3] = lod;
  87511. }
  87512. else {
  87513. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87514. }
  87515. index += 4;
  87516. }
  87517. }
  87518. return destArray;
  87519. };
  87520. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87521. var byteArray = new Uint8Array(dataLength);
  87522. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87523. var index = 0;
  87524. for (var y = 0; y < height; y++) {
  87525. for (var x = 0; x < width; x++) {
  87526. var srcPos = (x + y * width) * 4;
  87527. byteArray[index] = srcData[srcPos + rOffset];
  87528. byteArray[index + 1] = srcData[srcPos + gOffset];
  87529. byteArray[index + 2] = srcData[srcPos + bOffset];
  87530. byteArray[index + 3] = srcData[srcPos + aOffset];
  87531. index += 4;
  87532. }
  87533. }
  87534. return byteArray;
  87535. };
  87536. DDSTools._ExtractLongWordOrder = function (value) {
  87537. if (value === 0 || value === 255 || value === -16777216) {
  87538. return 0;
  87539. }
  87540. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87541. };
  87542. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87543. var byteArray = new Uint8Array(dataLength);
  87544. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87545. var index = 0;
  87546. for (var y = 0; y < height; y++) {
  87547. for (var x = 0; x < width; x++) {
  87548. var srcPos = (x + y * width) * 3;
  87549. byteArray[index] = srcData[srcPos + rOffset];
  87550. byteArray[index + 1] = srcData[srcPos + gOffset];
  87551. byteArray[index + 2] = srcData[srcPos + bOffset];
  87552. index += 3;
  87553. }
  87554. }
  87555. return byteArray;
  87556. };
  87557. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87558. var byteArray = new Uint8Array(dataLength);
  87559. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87560. var index = 0;
  87561. for (var y = 0; y < height; y++) {
  87562. for (var x = 0; x < width; x++) {
  87563. var srcPos = (x + y * width);
  87564. byteArray[index] = srcData[srcPos];
  87565. index++;
  87566. }
  87567. }
  87568. return byteArray;
  87569. };
  87570. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87571. if (lodIndex === void 0) { lodIndex = -1; }
  87572. var sphericalPolynomialFaces = null;
  87573. if (info.sphericalPolynomial) {
  87574. sphericalPolynomialFaces = new Array();
  87575. }
  87576. var ext = engine.getCaps().s3tc;
  87577. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87578. var fourCC, width, height, dataLength = 0, dataOffset;
  87579. var byteArray, mipmapCount, mip;
  87580. var internalFormat = 0;
  87581. var format = 0;
  87582. var blockBytes = 1;
  87583. if (header[off_magic] !== DDS_MAGIC) {
  87584. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87585. return;
  87586. }
  87587. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87588. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87589. return;
  87590. }
  87591. if (info.isCompressed && !ext) {
  87592. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87593. return;
  87594. }
  87595. var bpp = header[off_RGBbpp];
  87596. dataOffset = header[off_size] + 4;
  87597. var computeFormats = false;
  87598. if (info.isFourCC) {
  87599. fourCC = header[off_pfFourCC];
  87600. switch (fourCC) {
  87601. case FOURCC_DXT1:
  87602. blockBytes = 8;
  87603. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87604. break;
  87605. case FOURCC_DXT3:
  87606. blockBytes = 16;
  87607. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87608. break;
  87609. case FOURCC_DXT5:
  87610. blockBytes = 16;
  87611. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87612. break;
  87613. case FOURCC_D3DFMT_R16G16B16A16F:
  87614. computeFormats = true;
  87615. break;
  87616. case FOURCC_D3DFMT_R32G32B32A32F:
  87617. computeFormats = true;
  87618. break;
  87619. case FOURCC_DX10:
  87620. // There is an additionnal header so dataOffset need to be changed
  87621. dataOffset += 5 * 4; // 5 uints
  87622. var supported = false;
  87623. switch (info.dxgiFormat) {
  87624. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87625. computeFormats = true;
  87626. supported = true;
  87627. break;
  87628. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87629. info.isRGB = true;
  87630. info.isFourCC = false;
  87631. bpp = 32;
  87632. supported = true;
  87633. break;
  87634. }
  87635. if (supported) {
  87636. break;
  87637. }
  87638. default:
  87639. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87640. return;
  87641. }
  87642. }
  87643. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87644. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87645. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87646. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87647. if (computeFormats) {
  87648. format = engine._getWebGLTextureType(info.textureType);
  87649. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87650. }
  87651. mipmapCount = 1;
  87652. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87653. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87654. }
  87655. for (var face = 0; face < faces; face++) {
  87656. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87657. width = header[off_width];
  87658. height = header[off_height];
  87659. for (mip = 0; mip < mipmapCount; ++mip) {
  87660. if (lodIndex === -1 || lodIndex === mip) {
  87661. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87662. var i = (lodIndex === -1) ? mip : 0;
  87663. if (!info.isCompressed && info.isFourCC) {
  87664. dataLength = width * height * 4;
  87665. var floatArray = null;
  87666. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87667. if (bpp === 128) {
  87668. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87669. if (sphericalPolynomialFaces && i == 0) {
  87670. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87671. }
  87672. }
  87673. else if (bpp === 64) {
  87674. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87675. if (sphericalPolynomialFaces && i == 0) {
  87676. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87677. }
  87678. }
  87679. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87680. format = engine._getWebGLTextureType(info.textureType);
  87681. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87682. }
  87683. else {
  87684. if (bpp === 128) {
  87685. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87686. if (sphericalPolynomialFaces && i == 0) {
  87687. sphericalPolynomialFaces.push(floatArray);
  87688. }
  87689. }
  87690. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87691. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87692. if (sphericalPolynomialFaces && i == 0) {
  87693. sphericalPolynomialFaces.push(floatArray);
  87694. }
  87695. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87696. format = engine._getWebGLTextureType(info.textureType);
  87697. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87698. }
  87699. else { // 64
  87700. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87701. if (sphericalPolynomialFaces && i == 0) {
  87702. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87703. }
  87704. }
  87705. }
  87706. if (floatArray) {
  87707. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87708. }
  87709. }
  87710. else if (info.isRGB) {
  87711. if (bpp === 24) {
  87712. dataLength = width * height * 3;
  87713. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87714. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87715. }
  87716. else { // 32
  87717. dataLength = width * height * 4;
  87718. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87719. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87720. }
  87721. }
  87722. else if (info.isLuminance) {
  87723. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87724. var unpaddedRowSize = width;
  87725. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87726. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87727. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87728. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87729. }
  87730. else {
  87731. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87732. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87733. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87734. }
  87735. }
  87736. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87737. width *= 0.5;
  87738. height *= 0.5;
  87739. width = Math.max(1.0, width);
  87740. height = Math.max(1.0, height);
  87741. }
  87742. if (currentFace !== undefined) {
  87743. // Loading a single face
  87744. break;
  87745. }
  87746. }
  87747. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87748. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87749. size: header[off_width],
  87750. right: sphericalPolynomialFaces[0],
  87751. left: sphericalPolynomialFaces[1],
  87752. up: sphericalPolynomialFaces[2],
  87753. down: sphericalPolynomialFaces[3],
  87754. front: sphericalPolynomialFaces[4],
  87755. back: sphericalPolynomialFaces[5],
  87756. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87757. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87758. gammaSpace: false,
  87759. });
  87760. }
  87761. else {
  87762. info.sphericalPolynomial = undefined;
  87763. }
  87764. };
  87765. DDSTools.StoreLODInAlphaChannel = false;
  87766. return DDSTools;
  87767. }());
  87768. BABYLON.DDSTools = DDSTools;
  87769. })(BABYLON || (BABYLON = {}));
  87770. //# sourceMappingURL=babylon.dds.js.map
  87771. var BABYLON;
  87772. (function (BABYLON) {
  87773. /**
  87774. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87775. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87776. */
  87777. var KhronosTextureContainer = /** @class */ (function () {
  87778. /**
  87779. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87780. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87781. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87782. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87783. */
  87784. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87785. this.arrayBuffer = arrayBuffer;
  87786. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87787. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87788. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87789. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87790. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87791. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87792. BABYLON.Tools.Error("texture missing KTX identifier");
  87793. return;
  87794. }
  87795. // load the reset of the header in native 32 bit int
  87796. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87797. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87798. var oppositeEndianess = header[0] === 0x01020304;
  87799. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87800. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87801. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87802. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87803. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87804. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87805. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87806. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87807. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87808. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87809. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87810. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87811. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87812. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87813. if (this.glType !== 0) {
  87814. BABYLON.Tools.Error("only compressed formats currently supported");
  87815. return;
  87816. }
  87817. else {
  87818. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87819. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87820. }
  87821. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87822. BABYLON.Tools.Error("only 2D textures currently supported");
  87823. return;
  87824. }
  87825. if (this.numberOfArrayElements !== 0) {
  87826. BABYLON.Tools.Error("texture arrays not currently supported");
  87827. return;
  87828. }
  87829. if (this.numberOfFaces !== facesExpected) {
  87830. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87831. return;
  87832. }
  87833. // we now have a completely validated file, so could use existence of loadType as success
  87834. // would need to make this more elaborate & adjust checks above to support more than one load type
  87835. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87836. }
  87837. // not as fast hardware based, but will probably never need to use
  87838. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87839. return ((val & 0xFF) << 24)
  87840. | ((val & 0xFF00) << 8)
  87841. | ((val >> 8) & 0xFF00)
  87842. | ((val >> 24) & 0xFF);
  87843. };
  87844. /**
  87845. * It is assumed that the texture has already been created & is currently bound
  87846. */
  87847. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87848. switch (this.loadType) {
  87849. case KhronosTextureContainer.COMPRESSED_2D:
  87850. this._upload2DCompressedLevels(gl, loadMipmaps);
  87851. break;
  87852. case KhronosTextureContainer.TEX_2D:
  87853. case KhronosTextureContainer.COMPRESSED_3D:
  87854. case KhronosTextureContainer.TEX_3D:
  87855. }
  87856. };
  87857. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87858. // initialize width & height for level 1
  87859. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87860. var width = this.pixelWidth;
  87861. var height = this.pixelHeight;
  87862. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87863. for (var level = 0; level < mipmapCount; level++) {
  87864. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87865. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87866. for (var face = 0; face < this.numberOfFaces; face++) {
  87867. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87868. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87869. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87870. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87871. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87872. }
  87873. width = Math.max(1.0, width * 0.5);
  87874. height = Math.max(1.0, height * 0.5);
  87875. }
  87876. };
  87877. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87878. // load types
  87879. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87880. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87881. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87882. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87883. return KhronosTextureContainer;
  87884. }());
  87885. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87886. })(BABYLON || (BABYLON = {}));
  87887. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87888. var BABYLON;
  87889. (function (BABYLON) {
  87890. var Debug;
  87891. (function (Debug) {
  87892. /**
  87893. * Class used to render a debug view of a given skeleton
  87894. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87895. */
  87896. var SkeletonViewer = /** @class */ (function () {
  87897. /**
  87898. * Creates a new SkeletonViewer
  87899. * @param skeleton defines the skeleton to render
  87900. * @param mesh defines the mesh attached to the skeleton
  87901. * @param scene defines the hosting scene
  87902. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87903. * @param renderingGroupId defines the rendering group id to use with the viewer
  87904. */
  87905. function SkeletonViewer(
  87906. /** defines the skeleton to render */
  87907. skeleton,
  87908. /** defines the mesh attached to the skeleton */
  87909. mesh, scene,
  87910. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87911. autoUpdateBonesMatrices,
  87912. /** defines the rendering group id to use with the viewer */
  87913. renderingGroupId) {
  87914. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87915. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87916. this.skeleton = skeleton;
  87917. this.mesh = mesh;
  87918. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87919. this.renderingGroupId = renderingGroupId;
  87920. /** Gets or sets the color used to render the skeleton */
  87921. this.color = BABYLON.Color3.White();
  87922. this._debugLines = new Array();
  87923. this._isEnabled = false;
  87924. this._scene = scene;
  87925. this.update();
  87926. this._renderFunction = this.update.bind(this);
  87927. }
  87928. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87929. get: function () {
  87930. return this._isEnabled;
  87931. },
  87932. /** Gets or sets a boolean indicating if the viewer is enabled */
  87933. set: function (value) {
  87934. if (this._isEnabled === value) {
  87935. return;
  87936. }
  87937. this._isEnabled = value;
  87938. if (value) {
  87939. this._scene.registerBeforeRender(this._renderFunction);
  87940. }
  87941. else {
  87942. this._scene.unregisterBeforeRender(this._renderFunction);
  87943. }
  87944. },
  87945. enumerable: true,
  87946. configurable: true
  87947. });
  87948. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87949. if (x === void 0) { x = 0; }
  87950. if (y === void 0) { y = 0; }
  87951. if (z === void 0) { z = 0; }
  87952. var tmat = BABYLON.Tmp.Matrix[0];
  87953. var parentBone = bone.getParent();
  87954. tmat.copyFrom(bone.getLocalMatrix());
  87955. if (x !== 0 || y !== 0 || z !== 0) {
  87956. var tmat2 = BABYLON.Tmp.Matrix[1];
  87957. BABYLON.Matrix.IdentityToRef(tmat2);
  87958. tmat2.m[12] = x;
  87959. tmat2.m[13] = y;
  87960. tmat2.m[14] = z;
  87961. tmat2.multiplyToRef(tmat, tmat);
  87962. }
  87963. if (parentBone) {
  87964. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87965. }
  87966. tmat.multiplyToRef(meshMat, tmat);
  87967. position.x = tmat.m[12];
  87968. position.y = tmat.m[13];
  87969. position.z = tmat.m[14];
  87970. };
  87971. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87972. var len = bones.length;
  87973. var meshPos = this.mesh.position;
  87974. for (var i = 0; i < len; i++) {
  87975. var bone = bones[i];
  87976. var points = this._debugLines[i];
  87977. if (!points) {
  87978. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87979. this._debugLines[i] = points;
  87980. }
  87981. this._getBonePosition(points[0], bone, meshMat);
  87982. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87983. points[0].subtractInPlace(meshPos);
  87984. points[1].subtractInPlace(meshPos);
  87985. }
  87986. };
  87987. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87988. var len = bones.length;
  87989. var boneNum = 0;
  87990. var meshPos = this.mesh.position;
  87991. for (var i = len - 1; i >= 0; i--) {
  87992. var childBone = bones[i];
  87993. var parentBone = childBone.getParent();
  87994. if (!parentBone) {
  87995. continue;
  87996. }
  87997. var points = this._debugLines[boneNum];
  87998. if (!points) {
  87999. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88000. this._debugLines[boneNum] = points;
  88001. }
  88002. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  88003. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  88004. points[0].subtractInPlace(meshPos);
  88005. points[1].subtractInPlace(meshPos);
  88006. boneNum++;
  88007. }
  88008. };
  88009. /** Update the viewer to sync with current skeleton state */
  88010. SkeletonViewer.prototype.update = function () {
  88011. if (this.autoUpdateBonesMatrices) {
  88012. this.skeleton.computeAbsoluteTransforms();
  88013. }
  88014. if (this.skeleton.bones[0].length === undefined) {
  88015. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  88016. }
  88017. else {
  88018. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  88019. }
  88020. if (!this._debugMesh) {
  88021. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  88022. this._debugMesh.renderingGroupId = this.renderingGroupId;
  88023. }
  88024. else {
  88025. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  88026. }
  88027. this._debugMesh.position.copyFrom(this.mesh.position);
  88028. this._debugMesh.color = this.color;
  88029. };
  88030. /** Release associated resources */
  88031. SkeletonViewer.prototype.dispose = function () {
  88032. if (this._debugMesh) {
  88033. this.isEnabled = false;
  88034. this._debugMesh.dispose();
  88035. this._debugMesh = null;
  88036. }
  88037. };
  88038. return SkeletonViewer;
  88039. }());
  88040. Debug.SkeletonViewer = SkeletonViewer;
  88041. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88042. })(BABYLON || (BABYLON = {}));
  88043. //# sourceMappingURL=babylon.skeletonViewer.js.map
  88044. /**
  88045. * Module Debug contains the (visual) components to debug a scene correctly
  88046. */
  88047. var BABYLON;
  88048. (function (BABYLON) {
  88049. var Debug;
  88050. (function (Debug) {
  88051. /**
  88052. * The Axes viewer will show 3 axes in a specific point in space
  88053. */
  88054. var AxesViewer = /** @class */ (function () {
  88055. /**
  88056. * Creates a new AxesViewer
  88057. * @param scene defines the hosting scene
  88058. * @param scaleLines defines a number used to scale line length (1 by default)
  88059. */
  88060. function AxesViewer(scene, scaleLines) {
  88061. if (scaleLines === void 0) { scaleLines = 1; }
  88062. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88063. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88064. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88065. /**
  88066. * Gets or sets a number used to scale line length
  88067. */
  88068. this.scaleLines = 1;
  88069. this.scaleLines = scaleLines;
  88070. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  88071. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  88072. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  88073. this._xmesh.renderingGroupId = 2;
  88074. this._ymesh.renderingGroupId = 2;
  88075. this._zmesh.renderingGroupId = 2;
  88076. this._xmesh.material.checkReadyOnlyOnce = true;
  88077. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  88078. this._ymesh.material.checkReadyOnlyOnce = true;
  88079. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  88080. this._zmesh.material.checkReadyOnlyOnce = true;
  88081. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  88082. this.scene = scene;
  88083. }
  88084. /**
  88085. * Force the viewer to update
  88086. * @param position defines the position of the viewer
  88087. * @param xaxis defines the x axis of the viewer
  88088. * @param yaxis defines the y axis of the viewer
  88089. * @param zaxis defines the z axis of the viewer
  88090. */
  88091. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  88092. var scaleLines = this.scaleLines;
  88093. if (this._xmesh) {
  88094. this._xmesh.position.copyFrom(position);
  88095. }
  88096. if (this._ymesh) {
  88097. this._ymesh.position.copyFrom(position);
  88098. }
  88099. if (this._zmesh) {
  88100. this._zmesh.position.copyFrom(position);
  88101. }
  88102. var point2 = this._xline[1];
  88103. point2.x = xaxis.x * scaleLines;
  88104. point2.y = xaxis.y * scaleLines;
  88105. point2.z = xaxis.z * scaleLines;
  88106. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  88107. point2 = this._yline[1];
  88108. point2.x = yaxis.x * scaleLines;
  88109. point2.y = yaxis.y * scaleLines;
  88110. point2.z = yaxis.z * scaleLines;
  88111. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  88112. point2 = this._zline[1];
  88113. point2.x = zaxis.x * scaleLines;
  88114. point2.y = zaxis.y * scaleLines;
  88115. point2.z = zaxis.z * scaleLines;
  88116. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  88117. };
  88118. /** Releases resources */
  88119. AxesViewer.prototype.dispose = function () {
  88120. if (this._xmesh) {
  88121. this._xmesh.dispose();
  88122. }
  88123. if (this._ymesh) {
  88124. this._ymesh.dispose();
  88125. }
  88126. if (this._zmesh) {
  88127. this._zmesh.dispose();
  88128. }
  88129. this._xmesh = null;
  88130. this._ymesh = null;
  88131. this._zmesh = null;
  88132. this.scene = null;
  88133. };
  88134. return AxesViewer;
  88135. }());
  88136. Debug.AxesViewer = AxesViewer;
  88137. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88138. })(BABYLON || (BABYLON = {}));
  88139. //# sourceMappingURL=babylon.axesViewer.js.map
  88140. var BABYLON;
  88141. (function (BABYLON) {
  88142. var Debug;
  88143. (function (Debug) {
  88144. /**
  88145. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  88146. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  88147. */
  88148. var BoneAxesViewer = /** @class */ (function (_super) {
  88149. __extends(BoneAxesViewer, _super);
  88150. /**
  88151. * Creates a new BoneAxesViewer
  88152. * @param scene defines the hosting scene
  88153. * @param bone defines the target bone
  88154. * @param mesh defines the target mesh
  88155. * @param scaleLines defines a scaling factor for line length (1 by default)
  88156. */
  88157. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  88158. if (scaleLines === void 0) { scaleLines = 1; }
  88159. var _this = _super.call(this, scene, scaleLines) || this;
  88160. /** Gets current position */
  88161. _this.pos = BABYLON.Vector3.Zero();
  88162. /** Gets direction of X axis */
  88163. _this.xaxis = BABYLON.Vector3.Zero();
  88164. /** Gets direction of Y axis */
  88165. _this.yaxis = BABYLON.Vector3.Zero();
  88166. /** Gets direction of Z axis */
  88167. _this.zaxis = BABYLON.Vector3.Zero();
  88168. _this.mesh = mesh;
  88169. _this.bone = bone;
  88170. return _this;
  88171. }
  88172. /**
  88173. * Force the viewer to update
  88174. */
  88175. BoneAxesViewer.prototype.update = function () {
  88176. if (!this.mesh || !this.bone) {
  88177. return;
  88178. }
  88179. var bone = this.bone;
  88180. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  88181. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  88182. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  88183. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  88184. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  88185. };
  88186. /** Releases resources */
  88187. BoneAxesViewer.prototype.dispose = function () {
  88188. if (this.mesh) {
  88189. this.mesh = null;
  88190. this.bone = null;
  88191. _super.prototype.dispose.call(this);
  88192. }
  88193. };
  88194. return BoneAxesViewer;
  88195. }(Debug.AxesViewer));
  88196. Debug.BoneAxesViewer = BoneAxesViewer;
  88197. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88198. })(BABYLON || (BABYLON = {}));
  88199. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  88200. var BABYLON;
  88201. (function (BABYLON) {
  88202. var RayHelper = /** @class */ (function () {
  88203. function RayHelper(ray) {
  88204. this.ray = ray;
  88205. }
  88206. RayHelper.CreateAndShow = function (ray, scene, color) {
  88207. var helper = new RayHelper(ray);
  88208. helper.show(scene, color);
  88209. return helper;
  88210. };
  88211. RayHelper.prototype.show = function (scene, color) {
  88212. if (!this._renderFunction && this.ray) {
  88213. var ray = this.ray;
  88214. this._renderFunction = this._render.bind(this);
  88215. this._scene = scene;
  88216. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  88217. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  88218. if (this._renderFunction) {
  88219. this._scene.registerBeforeRender(this._renderFunction);
  88220. }
  88221. }
  88222. if (color && this._renderLine) {
  88223. this._renderLine.color.copyFrom(color);
  88224. }
  88225. };
  88226. RayHelper.prototype.hide = function () {
  88227. if (this._renderFunction && this._scene) {
  88228. this._scene.unregisterBeforeRender(this._renderFunction);
  88229. this._scene = null;
  88230. this._renderFunction = null;
  88231. if (this._renderLine) {
  88232. this._renderLine.dispose();
  88233. this._renderLine = null;
  88234. }
  88235. this._renderPoints = [];
  88236. }
  88237. };
  88238. RayHelper.prototype._render = function () {
  88239. var ray = this.ray;
  88240. if (!ray) {
  88241. return;
  88242. }
  88243. var point = this._renderPoints[1];
  88244. var len = Math.min(ray.length, 1000000);
  88245. point.copyFrom(ray.direction);
  88246. point.scaleInPlace(len);
  88247. point.addInPlace(ray.origin);
  88248. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  88249. };
  88250. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  88251. this._attachedToMesh = mesh;
  88252. var ray = this.ray;
  88253. if (!ray) {
  88254. return;
  88255. }
  88256. if (!ray.direction) {
  88257. ray.direction = BABYLON.Vector3.Zero();
  88258. }
  88259. if (!ray.origin) {
  88260. ray.origin = BABYLON.Vector3.Zero();
  88261. }
  88262. if (length) {
  88263. ray.length = length;
  88264. }
  88265. if (!meshSpaceOrigin) {
  88266. meshSpaceOrigin = BABYLON.Vector3.Zero();
  88267. }
  88268. if (!meshSpaceDirection) {
  88269. // -1 so that this will work with Mesh.lookAt
  88270. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  88271. }
  88272. if (!this._meshSpaceDirection) {
  88273. this._meshSpaceDirection = meshSpaceDirection.clone();
  88274. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  88275. }
  88276. else {
  88277. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  88278. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  88279. }
  88280. if (!this._updateToMeshFunction) {
  88281. this._updateToMeshFunction = this._updateToMesh.bind(this);
  88282. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  88283. }
  88284. this._updateToMesh();
  88285. };
  88286. RayHelper.prototype.detachFromMesh = function () {
  88287. if (this._attachedToMesh) {
  88288. if (this._updateToMeshFunction) {
  88289. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  88290. }
  88291. this._attachedToMesh = null;
  88292. this._updateToMeshFunction = null;
  88293. }
  88294. };
  88295. RayHelper.prototype._updateToMesh = function () {
  88296. var ray = this.ray;
  88297. if (!this._attachedToMesh || !ray) {
  88298. return;
  88299. }
  88300. if (this._attachedToMesh._isDisposed) {
  88301. this.detachFromMesh();
  88302. return;
  88303. }
  88304. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88305. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88306. };
  88307. RayHelper.prototype.dispose = function () {
  88308. this.hide();
  88309. this.detachFromMesh();
  88310. this.ray = null;
  88311. };
  88312. return RayHelper;
  88313. }());
  88314. BABYLON.RayHelper = RayHelper;
  88315. })(BABYLON || (BABYLON = {}));
  88316. //# sourceMappingURL=babylon.rayHelper.js.map
  88317. var BABYLON;
  88318. (function (BABYLON) {
  88319. // load the inspector using require, if not present in the global namespace.
  88320. var DebugLayer = /** @class */ (function () {
  88321. function DebugLayer(scene) {
  88322. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88323. this._scene = scene;
  88324. // load inspector using require, if it doesn't exist on the global namespace.
  88325. }
  88326. /** Creates the inspector window. */
  88327. DebugLayer.prototype._createInspector = function (config) {
  88328. if (config === void 0) { config = {}; }
  88329. var popup = config.popup || false;
  88330. var initialTab = config.initialTab || 0;
  88331. var parentElement = config.parentElement || null;
  88332. if (!this._inspector) {
  88333. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88334. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88335. } // else nothing to do,; instance is already existing
  88336. };
  88337. DebugLayer.prototype.isVisible = function () {
  88338. if (!this._inspector) {
  88339. return false;
  88340. }
  88341. return true;
  88342. };
  88343. DebugLayer.prototype.hide = function () {
  88344. if (this._inspector) {
  88345. try {
  88346. this._inspector.dispose();
  88347. }
  88348. catch (e) {
  88349. // If the inspector has been removed directly from the inspector tool
  88350. }
  88351. this.onPropertyChangedObservable.clear();
  88352. this._inspector = null;
  88353. }
  88354. };
  88355. /**
  88356. *
  88357. * Launch the debugLayer.
  88358. *
  88359. * initialTab:
  88360. * | Value | Tab Name |
  88361. * | --- | --- |
  88362. * | 0 | Scene |
  88363. * | 1 | Console |
  88364. * | 2 | Stats |
  88365. * | 3 | Textures |
  88366. * | 4 | Mesh |
  88367. * | 5 | Light |
  88368. * | 6 | Material |
  88369. * | 7 | GLTF |
  88370. * | 8 | GUI |
  88371. * | 9 | Physics |
  88372. * | 10 | Camera |
  88373. * | 11 | Audio |
  88374. *
  88375. */
  88376. DebugLayer.prototype.show = function (config) {
  88377. if (config === void 0) { config = {}; }
  88378. if (typeof this.BJSINSPECTOR == 'undefined') {
  88379. // Load inspector and add it to the DOM
  88380. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88381. }
  88382. else {
  88383. // Otherwise creates the inspector
  88384. this._createInspector(config);
  88385. this.onPropertyChangedObservable = new BABYLON.Observable();
  88386. }
  88387. };
  88388. /**
  88389. * Gets the active tab
  88390. * @return the index of the active tab or -1 if the inspector is hidden
  88391. */
  88392. DebugLayer.prototype.getActiveTab = function () {
  88393. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88394. };
  88395. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88396. return DebugLayer;
  88397. }());
  88398. BABYLON.DebugLayer = DebugLayer;
  88399. })(BABYLON || (BABYLON = {}));
  88400. //# sourceMappingURL=babylon.debugLayer.js.map
  88401. var BABYLON;
  88402. (function (BABYLON) {
  88403. var Debug;
  88404. (function (Debug) {
  88405. /**
  88406. * Used to show the physics impostor around the specific mesh
  88407. */
  88408. var PhysicsViewer = /** @class */ (function () {
  88409. /**
  88410. * Creates a new PhysicsViewer
  88411. * @param scene defines the hosting scene
  88412. */
  88413. function PhysicsViewer(scene) {
  88414. /** @hidden */
  88415. this._impostors = [];
  88416. /** @hidden */
  88417. this._meshes = [];
  88418. /** @hidden */
  88419. this._numMeshes = 0;
  88420. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88421. var physicEngine = this._scene.getPhysicsEngine();
  88422. if (physicEngine) {
  88423. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88424. }
  88425. }
  88426. /** @hidden */
  88427. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88428. var plugin = this._physicsEnginePlugin;
  88429. for (var i = 0; i < this._numMeshes; i++) {
  88430. var impostor = this._impostors[i];
  88431. if (!impostor) {
  88432. continue;
  88433. }
  88434. if (impostor.isDisposed) {
  88435. this.hideImpostor(this._impostors[i--]);
  88436. }
  88437. else {
  88438. var mesh = this._meshes[i];
  88439. if (mesh && plugin) {
  88440. plugin.syncMeshWithImpostor(mesh, impostor);
  88441. }
  88442. }
  88443. }
  88444. };
  88445. /**
  88446. * Renders a specified physic impostor
  88447. * @param impostor defines the impostor to render
  88448. */
  88449. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88450. if (!this._scene) {
  88451. return;
  88452. }
  88453. for (var i = 0; i < this._numMeshes; i++) {
  88454. if (this._impostors[i] == impostor) {
  88455. return;
  88456. }
  88457. }
  88458. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88459. if (debugMesh) {
  88460. this._impostors[this._numMeshes] = impostor;
  88461. this._meshes[this._numMeshes] = debugMesh;
  88462. if (this._numMeshes === 0) {
  88463. this._renderFunction = this._updateDebugMeshes.bind(this);
  88464. this._scene.registerBeforeRender(this._renderFunction);
  88465. }
  88466. this._numMeshes++;
  88467. }
  88468. };
  88469. /**
  88470. * Hides a specified physic impostor
  88471. * @param impostor defines the impostor to hide
  88472. */
  88473. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88474. if (!impostor || !this._scene) {
  88475. return;
  88476. }
  88477. var removed = false;
  88478. for (var i = 0; i < this._numMeshes; i++) {
  88479. if (this._impostors[i] == impostor) {
  88480. var mesh = this._meshes[i];
  88481. if (!mesh) {
  88482. continue;
  88483. }
  88484. this._scene.removeMesh(mesh);
  88485. mesh.dispose();
  88486. this._numMeshes--;
  88487. if (this._numMeshes > 0) {
  88488. this._meshes[i] = this._meshes[this._numMeshes];
  88489. this._impostors[i] = this._impostors[this._numMeshes];
  88490. this._meshes[this._numMeshes] = null;
  88491. this._impostors[this._numMeshes] = null;
  88492. }
  88493. else {
  88494. this._meshes[0] = null;
  88495. this._impostors[0] = null;
  88496. }
  88497. removed = true;
  88498. break;
  88499. }
  88500. }
  88501. if (removed && this._numMeshes === 0) {
  88502. this._scene.unregisterBeforeRender(this._renderFunction);
  88503. }
  88504. };
  88505. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88506. if (!this._debugMaterial) {
  88507. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88508. this._debugMaterial.wireframe = true;
  88509. }
  88510. return this._debugMaterial;
  88511. };
  88512. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88513. if (!this._debugBoxMesh) {
  88514. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88515. this._debugBoxMesh.renderingGroupId = 1;
  88516. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88517. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88518. scene.removeMesh(this._debugBoxMesh);
  88519. }
  88520. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88521. };
  88522. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88523. if (!this._debugSphereMesh) {
  88524. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88525. this._debugSphereMesh.renderingGroupId = 1;
  88526. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88527. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88528. scene.removeMesh(this._debugSphereMesh);
  88529. }
  88530. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88531. };
  88532. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88533. var mesh = null;
  88534. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88535. mesh = this._getDebugBoxMesh(scene);
  88536. impostor.getBoxSizeToRef(mesh.scaling);
  88537. }
  88538. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88539. mesh = this._getDebugSphereMesh(scene);
  88540. var radius = impostor.getRadius();
  88541. mesh.scaling.x = radius * 2;
  88542. mesh.scaling.y = radius * 2;
  88543. mesh.scaling.z = radius * 2;
  88544. }
  88545. return mesh;
  88546. };
  88547. /** Releases all resources */
  88548. PhysicsViewer.prototype.dispose = function () {
  88549. for (var i = 0; i < this._numMeshes; i++) {
  88550. this.hideImpostor(this._impostors[i]);
  88551. }
  88552. if (this._debugBoxMesh) {
  88553. this._debugBoxMesh.dispose();
  88554. }
  88555. if (this._debugSphereMesh) {
  88556. this._debugSphereMesh.dispose();
  88557. }
  88558. if (this._debugMaterial) {
  88559. this._debugMaterial.dispose();
  88560. }
  88561. this._impostors.length = 0;
  88562. this._scene = null;
  88563. this._physicsEnginePlugin = null;
  88564. };
  88565. return PhysicsViewer;
  88566. }());
  88567. Debug.PhysicsViewer = PhysicsViewer;
  88568. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88569. })(BABYLON || (BABYLON = {}));
  88570. //# sourceMappingURL=babylon.physicsViewer.js.map
  88571. var BABYLON;
  88572. (function (BABYLON) {
  88573. var BoundingBoxRenderer = /** @class */ (function () {
  88574. function BoundingBoxRenderer(scene) {
  88575. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88576. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88577. this.showBackLines = true;
  88578. this.renderList = new BABYLON.SmartArray(32);
  88579. this._vertexBuffers = {};
  88580. this._scene = scene;
  88581. }
  88582. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88583. if (this._colorShader) {
  88584. return;
  88585. }
  88586. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  88587. attributes: [BABYLON.VertexBuffer.PositionKind],
  88588. uniforms: ["world", "viewProjection", "color"]
  88589. });
  88590. var engine = this._scene.getEngine();
  88591. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88592. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88593. this._createIndexBuffer();
  88594. };
  88595. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88596. var engine = this._scene.getEngine();
  88597. 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]);
  88598. };
  88599. BoundingBoxRenderer.prototype._rebuild = function () {
  88600. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88601. if (vb) {
  88602. vb._rebuild();
  88603. }
  88604. this._createIndexBuffer();
  88605. };
  88606. BoundingBoxRenderer.prototype.reset = function () {
  88607. this.renderList.reset();
  88608. };
  88609. BoundingBoxRenderer.prototype.render = function () {
  88610. if (this.renderList.length === 0) {
  88611. return;
  88612. }
  88613. this._prepareRessources();
  88614. if (!this._colorShader.isReady()) {
  88615. return;
  88616. }
  88617. var engine = this._scene.getEngine();
  88618. engine.setDepthWrite(false);
  88619. this._colorShader._preBind();
  88620. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88621. var boundingBox = this.renderList.data[boundingBoxIndex];
  88622. var min = boundingBox.minimum;
  88623. var max = boundingBox.maximum;
  88624. var diff = max.subtract(min);
  88625. var median = min.add(diff.scale(0.5));
  88626. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88627. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88628. .multiply(boundingBox.getWorldMatrix());
  88629. // VBOs
  88630. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88631. if (this.showBackLines) {
  88632. // Back
  88633. engine.setDepthFunctionToGreaterOrEqual();
  88634. this._scene.resetCachedMaterial();
  88635. this._colorShader.setColor4("color", this.backColor.toColor4());
  88636. this._colorShader.bind(worldMatrix);
  88637. // Draw order
  88638. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88639. }
  88640. // Front
  88641. engine.setDepthFunctionToLess();
  88642. this._scene.resetCachedMaterial();
  88643. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88644. this._colorShader.bind(worldMatrix);
  88645. // Draw order
  88646. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88647. }
  88648. this._colorShader.unbind();
  88649. engine.setDepthFunctionToLessOrEqual();
  88650. engine.setDepthWrite(true);
  88651. };
  88652. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88653. this._prepareRessources();
  88654. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88655. return;
  88656. }
  88657. var engine = this._scene.getEngine();
  88658. engine.setDepthWrite(false);
  88659. engine.setColorWrite(false);
  88660. this._colorShader._preBind();
  88661. var boundingBox = mesh._boundingInfo.boundingBox;
  88662. var min = boundingBox.minimum;
  88663. var max = boundingBox.maximum;
  88664. var diff = max.subtract(min);
  88665. var median = min.add(diff.scale(0.5));
  88666. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88667. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88668. .multiply(boundingBox.getWorldMatrix());
  88669. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88670. engine.setDepthFunctionToLess();
  88671. this._scene.resetCachedMaterial();
  88672. this._colorShader.bind(worldMatrix);
  88673. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88674. this._colorShader.unbind();
  88675. engine.setDepthFunctionToLessOrEqual();
  88676. engine.setDepthWrite(true);
  88677. engine.setColorWrite(true);
  88678. };
  88679. BoundingBoxRenderer.prototype.dispose = function () {
  88680. if (!this._colorShader) {
  88681. return;
  88682. }
  88683. this.renderList.dispose();
  88684. this._colorShader.dispose();
  88685. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88686. if (buffer) {
  88687. buffer.dispose();
  88688. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88689. }
  88690. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88691. };
  88692. return BoundingBoxRenderer;
  88693. }());
  88694. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88695. })(BABYLON || (BABYLON = {}));
  88696. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88697. var BABYLON;
  88698. (function (BABYLON) {
  88699. /**
  88700. * Renders a layer on top of an existing scene
  88701. */
  88702. var UtilityLayerRenderer = /** @class */ (function () {
  88703. /**
  88704. * Instantiates a UtilityLayerRenderer
  88705. * @param originalScene the original scene that will be rendered on top of
  88706. */
  88707. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88708. var _this = this;
  88709. this.originalScene = originalScene;
  88710. this._pointerCaptures = {};
  88711. this._lastPointerEvents = {};
  88712. /**
  88713. * If the utility layer should automatically be rendered on top of existing scene
  88714. */
  88715. this.shouldRender = true;
  88716. /**
  88717. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88718. */
  88719. this.onlyCheckPointerDownEvents = true;
  88720. /**
  88721. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88722. */
  88723. this.processAllEvents = false;
  88724. /**
  88725. * Observable raised when the pointer move from the utility layer scene to the main scene
  88726. */
  88727. this.onPointerOutObservable = new BABYLON.Observable();
  88728. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88729. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88730. originalScene.getEngine().scenes.pop();
  88731. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88732. this.utilityLayerScene.detachControl();
  88733. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88734. if (!_this.processAllEvents) {
  88735. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88736. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88737. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88738. return;
  88739. }
  88740. }
  88741. var pointerEvent = (prePointerInfo.event);
  88742. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88743. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88744. return;
  88745. }
  88746. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88747. if (!prePointerInfo.ray && utilityScenePick) {
  88748. prePointerInfo.ray = utilityScenePick.ray;
  88749. }
  88750. // always fire the prepointer oversvable
  88751. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88752. // allow every non pointer down event to flow to the utility layer
  88753. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88754. if (!prePointerInfo.skipOnPointerObservable) {
  88755. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88756. }
  88757. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88758. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88759. }
  88760. return;
  88761. }
  88762. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88763. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88764. if (utilityScenePick && utilityScenePick.hit) {
  88765. if (!prePointerInfo.skipOnPointerObservable) {
  88766. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88767. }
  88768. prePointerInfo.skipOnPointerObservable = true;
  88769. }
  88770. }
  88771. else {
  88772. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88773. var pointerEvent_1 = (prePointerInfo.event);
  88774. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88775. if (originalScenePick && utilityScenePick) {
  88776. // No pick in utility scene
  88777. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88778. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88779. // We touched an utility mesh present in the main scene
  88780. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88781. prePointerInfo.skipOnPointerObservable = true;
  88782. }
  88783. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88784. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88785. }
  88786. }
  88787. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88788. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88789. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88790. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88791. }
  88792. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88793. // We have a pick in both scenes but main is closer than utility
  88794. // We touched an utility mesh present in the main scene
  88795. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88796. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88797. prePointerInfo.skipOnPointerObservable = true;
  88798. }
  88799. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88800. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88801. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88802. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88803. }
  88804. }
  88805. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88806. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88807. }
  88808. }
  88809. }
  88810. });
  88811. // Render directly on top of existing scene without clearing
  88812. this.utilityLayerScene.autoClear = false;
  88813. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88814. if (_this.shouldRender) {
  88815. _this.render();
  88816. }
  88817. });
  88818. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88819. _this.dispose();
  88820. });
  88821. this._updateCamera();
  88822. }
  88823. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88824. get: function () {
  88825. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88826. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88827. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88828. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88829. });
  88830. }
  88831. return UtilityLayerRenderer._DefaultUtilityLayer;
  88832. },
  88833. enumerable: true,
  88834. configurable: true
  88835. });
  88836. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88837. if (!prePointerInfo.skipOnPointerObservable) {
  88838. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88839. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88840. }
  88841. };
  88842. /**
  88843. * Renders the utility layers scene on top of the original scene
  88844. */
  88845. UtilityLayerRenderer.prototype.render = function () {
  88846. this._updateCamera();
  88847. this.utilityLayerScene.render(false);
  88848. };
  88849. /**
  88850. * Disposes of the renderer
  88851. */
  88852. UtilityLayerRenderer.prototype.dispose = function () {
  88853. this.onPointerOutObservable.clear();
  88854. if (this._afterRenderObserver) {
  88855. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88856. }
  88857. if (this._sceneDisposeObserver) {
  88858. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88859. }
  88860. if (this._originalPointerObserver) {
  88861. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88862. }
  88863. this.utilityLayerScene.dispose();
  88864. };
  88865. UtilityLayerRenderer.prototype._updateCamera = function () {
  88866. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88867. };
  88868. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88869. return UtilityLayerRenderer;
  88870. }());
  88871. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88872. })(BABYLON || (BABYLON = {}));
  88873. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88874. //# sourceMappingURL=babylon.behavior.js.map
  88875. var BABYLON;
  88876. (function (BABYLON) {
  88877. /**
  88878. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88879. */
  88880. var PointerDragBehavior = /** @class */ (function () {
  88881. /**
  88882. * Creates a pointer drag behavior that can be attached to a mesh
  88883. * @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)
  88884. */
  88885. function PointerDragBehavior(options) {
  88886. this.options = options;
  88887. /**
  88888. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88889. */
  88890. this.currentDraggingPointerID = -1;
  88891. /**
  88892. * If the behavior is currently in a dragging state
  88893. */
  88894. this.dragging = false;
  88895. /**
  88896. * 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)
  88897. */
  88898. this.dragDeltaRatio = 0.2;
  88899. /**
  88900. * If the drag plane orientation should be updated during the dragging (Default: true)
  88901. */
  88902. this.updateDragPlane = true;
  88903. // Debug mode will display drag planes to help visualize behavior
  88904. this._debugMode = false;
  88905. this._moving = false;
  88906. /**
  88907. * Fires each time the attached mesh is dragged with the pointer
  88908. * * delta between last drag position and current drag position in world space
  88909. * * dragDistance along the drag axis
  88910. * * dragPlaneNormal normal of the current drag plane used during the drag
  88911. * * dragPlanePoint in world space where the drag intersects the drag plane
  88912. */
  88913. this.onDragObservable = new BABYLON.Observable();
  88914. /**
  88915. * Fires each time a drag begins (eg. mouse down on mesh)
  88916. */
  88917. this.onDragStartObservable = new BABYLON.Observable();
  88918. /**
  88919. * Fires each time a drag ends (eg. mouse release after drag)
  88920. */
  88921. this.onDragEndObservable = new BABYLON.Observable();
  88922. /**
  88923. * If the attached mesh should be moved when dragged
  88924. */
  88925. this.moveAttached = true;
  88926. /**
  88927. * If the drag behavior will react to drag events (Default: true)
  88928. */
  88929. this.enabled = true;
  88930. /**
  88931. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88932. */
  88933. this.useObjectOrienationForDragging = true;
  88934. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88935. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88936. // Variables to avoid instantiation in the below method
  88937. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88938. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88939. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88940. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88941. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88942. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88943. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88944. var optionCount = 0;
  88945. if (options === undefined) {
  88946. options = {};
  88947. }
  88948. if (options.dragAxis) {
  88949. optionCount++;
  88950. }
  88951. if (options.dragPlaneNormal) {
  88952. optionCount++;
  88953. }
  88954. if (optionCount > 1) {
  88955. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88956. }
  88957. }
  88958. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88959. /**
  88960. * The name of the behavior
  88961. */
  88962. get: function () {
  88963. return "PointerDrag";
  88964. },
  88965. enumerable: true,
  88966. configurable: true
  88967. });
  88968. /**
  88969. * Initializes the behavior
  88970. */
  88971. PointerDragBehavior.prototype.init = function () { };
  88972. /**
  88973. * Attaches the drag behavior the passed in mesh
  88974. * @param ownerNode The mesh that will be dragged around once attached
  88975. */
  88976. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88977. var _this = this;
  88978. this._scene = ownerNode.getScene();
  88979. this._attachedNode = ownerNode;
  88980. // Initialize drag plane to not interfere with existing scene
  88981. if (!PointerDragBehavior._planeScene) {
  88982. if (this._debugMode) {
  88983. PointerDragBehavior._planeScene = this._scene;
  88984. }
  88985. else {
  88986. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88987. this._scene.getEngine().scenes.pop();
  88988. }
  88989. }
  88990. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88991. // State of the drag
  88992. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88993. var delta = new BABYLON.Vector3(0, 0, 0);
  88994. var dragLength = 0;
  88995. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88996. var pickPredicate = function (m) {
  88997. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88998. };
  88999. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89000. if (!_this.enabled) {
  89001. return;
  89002. }
  89003. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89004. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89005. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89006. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89007. if (pickedPoint) {
  89008. _this.dragging = true;
  89009. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89010. _this.lastDragPosition.copyFrom(pickedPoint);
  89011. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89012. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89013. }
  89014. }
  89015. }
  89016. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89017. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89018. _this.releaseDrag();
  89019. }
  89020. }
  89021. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89022. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89023. _this._moving = true;
  89024. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89025. if (pickedPoint) {
  89026. if (_this.updateDragPlane) {
  89027. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89028. }
  89029. // depending on the drag mode option drag accordingly
  89030. if (_this.options.dragAxis) {
  89031. // Convert local drag axis to world
  89032. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89033. // Project delta drag from the drag plane onto the drag axis
  89034. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89035. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89036. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89037. }
  89038. else {
  89039. dragLength = delta.length();
  89040. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89041. }
  89042. targetPosition.addInPlace(delta);
  89043. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89044. _this.lastDragPosition.copyFrom(pickedPoint);
  89045. }
  89046. }
  89047. }
  89048. });
  89049. this._scene.onBeforeRenderObservable.add(function () {
  89050. if (_this._moving && _this.moveAttached) {
  89051. // Slowly move mesh to avoid jitter
  89052. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89053. _this._tmpVector.scaleInPlace(0.2);
  89054. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89055. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89056. }
  89057. });
  89058. };
  89059. PointerDragBehavior.prototype.releaseDrag = function () {
  89060. this.dragging = false;
  89061. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89062. this.currentDraggingPointerID = -1;
  89063. this._moving = false;
  89064. };
  89065. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89066. var _this = this;
  89067. if (!ray) {
  89068. return null;
  89069. }
  89070. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89071. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89072. return pickResult.pickedPoint;
  89073. }
  89074. else {
  89075. return null;
  89076. }
  89077. };
  89078. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89079. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89080. this._pointA.copyFrom(dragPlanePosition);
  89081. if (this.options.dragAxis) {
  89082. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  89083. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89084. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89085. ray.origin.subtractToRef(this._pointA, this._pointC);
  89086. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89087. // Get perpendicular line from direction to camera and drag axis
  89088. this._pointB.subtractToRef(this._pointA, this._lineA);
  89089. this._pointC.subtractToRef(this._pointA, this._lineB);
  89090. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89091. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89092. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89093. this._lookAt.normalize();
  89094. this._dragPlane.position.copyFrom(this._pointA);
  89095. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89096. this._dragPlane.lookAt(this._lookAt);
  89097. }
  89098. else if (this.options.dragPlaneNormal) {
  89099. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  89100. this._dragPlane.position.copyFrom(this._pointA);
  89101. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89102. this._dragPlane.lookAt(this._lookAt);
  89103. }
  89104. else {
  89105. this._dragPlane.position.copyFrom(this._pointA);
  89106. this._dragPlane.lookAt(ray.origin);
  89107. }
  89108. this._dragPlane.computeWorldMatrix(true);
  89109. };
  89110. /**
  89111. * Detaches the behavior from the mesh
  89112. */
  89113. PointerDragBehavior.prototype.detach = function () {
  89114. if (this._pointerObserver) {
  89115. this._scene.onPointerObservable.remove(this._pointerObserver);
  89116. }
  89117. };
  89118. return PointerDragBehavior;
  89119. }());
  89120. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89121. })(BABYLON || (BABYLON = {}));
  89122. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89123. var BABYLON;
  89124. (function (BABYLON) {
  89125. /**
  89126. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89127. */
  89128. var MultiPointerScaleBehavior = /** @class */ (function () {
  89129. function MultiPointerScaleBehavior() {
  89130. this._startDistance = 0;
  89131. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89132. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89133. this._sceneRenderObserver = null;
  89134. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89135. this._dragBehaviorA.moveAttached = false;
  89136. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89137. this._dragBehaviorB.moveAttached = false;
  89138. }
  89139. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89140. /**
  89141. * The name of the behavior
  89142. */
  89143. get: function () {
  89144. return "MultiPointerScale";
  89145. },
  89146. enumerable: true,
  89147. configurable: true
  89148. });
  89149. /**
  89150. * Initializes the behavior
  89151. */
  89152. MultiPointerScaleBehavior.prototype.init = function () { };
  89153. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89154. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89155. };
  89156. /**
  89157. * Attaches the scale behavior the passed in mesh
  89158. * @param ownerNode The mesh that will be scaled around once attached
  89159. */
  89160. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89161. var _this = this;
  89162. this._ownerNode = ownerNode;
  89163. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89164. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89165. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89166. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89167. _this._dragBehaviorA.releaseDrag();
  89168. }
  89169. else {
  89170. _this._initialScale.copyFrom(ownerNode.scaling);
  89171. _this._startDistance = _this._getCurrentDistance();
  89172. }
  89173. }
  89174. });
  89175. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89176. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89177. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89178. _this._dragBehaviorB.releaseDrag();
  89179. }
  89180. else {
  89181. _this._initialScale.copyFrom(ownerNode.scaling);
  89182. _this._startDistance = _this._getCurrentDistance();
  89183. }
  89184. }
  89185. });
  89186. // Once both drag behaviors are active scale based on the distance between the two pointers
  89187. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89188. behavior.onDragObservable.add(function () {
  89189. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89190. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89191. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89192. }
  89193. });
  89194. });
  89195. ownerNode.addBehavior(this._dragBehaviorA);
  89196. ownerNode.addBehavior(this._dragBehaviorB);
  89197. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89198. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89199. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89200. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89201. if (change.length() > 0.01) {
  89202. ownerNode.scaling.addInPlace(change);
  89203. }
  89204. }
  89205. });
  89206. };
  89207. /**
  89208. * Detaches the behavior from the mesh
  89209. */
  89210. MultiPointerScaleBehavior.prototype.detach = function () {
  89211. var _this = this;
  89212. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89213. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89214. behavior.onDragStartObservable.clear();
  89215. behavior.onDragObservable.clear();
  89216. _this._ownerNode.removeBehavior(behavior);
  89217. });
  89218. };
  89219. return MultiPointerScaleBehavior;
  89220. }());
  89221. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89222. })(BABYLON || (BABYLON = {}));
  89223. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89224. var BABYLON;
  89225. (function (BABYLON) {
  89226. /**
  89227. * 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
  89228. */
  89229. var SixDofDragBehavior = /** @class */ (function () {
  89230. function SixDofDragBehavior() {
  89231. this._sceneRenderObserver = null;
  89232. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89233. this._moving = false;
  89234. this._startingOrientation = new BABYLON.Quaternion();
  89235. /**
  89236. * 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)
  89237. */
  89238. this.zDragFactor = 5;
  89239. /**
  89240. * If the behavior is currently in a dragging state
  89241. */
  89242. this.dragging = false;
  89243. /**
  89244. * 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)
  89245. */
  89246. this.dragDeltaRatio = 0.2;
  89247. /**
  89248. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89249. */
  89250. this.currentDraggingPointerID = -1;
  89251. }
  89252. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89253. /**
  89254. * The name of the behavior
  89255. */
  89256. get: function () {
  89257. return "SixDofDrag";
  89258. },
  89259. enumerable: true,
  89260. configurable: true
  89261. });
  89262. /**
  89263. * Initializes the behavior
  89264. */
  89265. SixDofDragBehavior.prototype.init = function () { };
  89266. /**
  89267. * Attaches the scale behavior the passed in mesh
  89268. * @param ownerNode The mesh that will be scaled around once attached
  89269. */
  89270. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89271. var _this = this;
  89272. this._ownerNode = ownerNode;
  89273. this._scene = this._ownerNode.getScene();
  89274. if (!SixDofDragBehavior._virtualScene) {
  89275. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89276. this._scene.getEngine().scenes.pop();
  89277. }
  89278. var pickedMesh = null;
  89279. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89280. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89281. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89282. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89283. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89284. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89285. var pickPredicate = function (m) {
  89286. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89287. };
  89288. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89289. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89290. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89291. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  89292. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89293. // Set position and orientation of the controller
  89294. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89295. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89296. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89297. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89298. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89299. if (!pickedMesh.rotationQuaternion) {
  89300. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89301. }
  89302. var oldParent = pickedMesh.parent;
  89303. pickedMesh.setParent(null);
  89304. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89305. pickedMesh.setParent(oldParent);
  89306. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89307. // Update state
  89308. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89309. _this.dragging = true;
  89310. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89311. }
  89312. }
  89313. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89314. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89315. _this.dragging = false;
  89316. _this._moving = false;
  89317. _this.currentDraggingPointerID = -1;
  89318. pickedMesh = null;
  89319. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89320. }
  89321. }
  89322. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89323. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89324. // Calculate controller drag distance in controller space
  89325. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89326. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89327. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  89328. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89329. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89330. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  89331. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  89332. if (_this._virtualDragMesh.position.z < 0) {
  89333. _this._virtualDragMesh.position.z = 0;
  89334. }
  89335. // Update the controller position
  89336. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89337. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89338. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89339. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89340. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89341. if (pickedMesh.parent) {
  89342. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89343. }
  89344. if (!_this._moving) {
  89345. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89346. }
  89347. _this._moving = true;
  89348. }
  89349. }
  89350. });
  89351. var tmpQuaternion = new BABYLON.Quaternion();
  89352. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89353. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89354. if (_this.dragging && _this._moving && pickedMesh) {
  89355. // Slowly move mesh to avoid jitter
  89356. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89357. // Get change in rotation
  89358. tmpQuaternion.copyFrom(_this._startingOrientation);
  89359. tmpQuaternion.x = -tmpQuaternion.x;
  89360. tmpQuaternion.y = -tmpQuaternion.y;
  89361. tmpQuaternion.z = -tmpQuaternion.z;
  89362. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89363. // Convert change in rotation to only y axis rotation
  89364. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89365. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89366. // Slowly move mesh to avoid jitter
  89367. var oldParent = pickedMesh.parent;
  89368. pickedMesh.setParent(null);
  89369. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89370. pickedMesh.setParent(oldParent);
  89371. }
  89372. });
  89373. };
  89374. /**
  89375. * Detaches the behavior from the mesh
  89376. */
  89377. SixDofDragBehavior.prototype.detach = function () {
  89378. this._scene.onPointerObservable.remove(this._pointerObserver);
  89379. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89380. this._virtualOriginMesh.dispose();
  89381. this._virtualDragMesh.dispose();
  89382. };
  89383. return SixDofDragBehavior;
  89384. }());
  89385. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89386. })(BABYLON || (BABYLON = {}));
  89387. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89388. var BABYLON;
  89389. (function (BABYLON) {
  89390. /**
  89391. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89392. */
  89393. var Gizmo = /** @class */ (function () {
  89394. /**
  89395. * Creates a gizmo
  89396. * @param gizmoLayer The utility layer the gizmo will be added to
  89397. */
  89398. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89399. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89400. var _this = this;
  89401. this.gizmoLayer = gizmoLayer;
  89402. this._scaleFactor = 3;
  89403. /**
  89404. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89405. */
  89406. this.updateGizmoRotationToMatchAttachedMesh = true;
  89407. /**
  89408. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89409. */
  89410. this.updateGizmoPositionToMatchAttachedMesh = true;
  89411. /**
  89412. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89413. */
  89414. this._updateScale = true;
  89415. this._interactionsEnabled = true;
  89416. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89417. var tempVector = new BABYLON.Vector3();
  89418. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89419. if (_this.attachedMesh) {
  89420. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89421. if (!_this._rootMesh.rotationQuaternion) {
  89422. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  89423. }
  89424. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  89425. }
  89426. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89427. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89428. }
  89429. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89430. _this._rootMesh.position.subtractToRef(_this.gizmoLayer.utilityLayerScene.activeCamera.position, tempVector);
  89431. var dist = tempVector.length() / _this._scaleFactor;
  89432. _this._rootMesh.scaling.set(dist, dist, dist);
  89433. }
  89434. }
  89435. });
  89436. this.attachedMesh = null;
  89437. }
  89438. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89439. /**
  89440. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89441. * * When set, interactions will be enabled
  89442. */
  89443. get: function () {
  89444. return this._attachedMesh;
  89445. },
  89446. set: function (value) {
  89447. this._attachedMesh = value;
  89448. this._rootMesh.setEnabled(value ? true : false);
  89449. this._attachedMeshChanged(value);
  89450. },
  89451. enumerable: true,
  89452. configurable: true
  89453. });
  89454. Gizmo.prototype._attachedMeshChanged = function (value) {
  89455. };
  89456. /**
  89457. * Disposes of the gizmo
  89458. */
  89459. Gizmo.prototype.dispose = function () {
  89460. this._rootMesh.dispose();
  89461. if (this._beforeRenderObserver) {
  89462. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89463. }
  89464. };
  89465. return Gizmo;
  89466. }());
  89467. BABYLON.Gizmo = Gizmo;
  89468. })(BABYLON || (BABYLON = {}));
  89469. //# sourceMappingURL=babylon.gizmo.js.map
  89470. var BABYLON;
  89471. (function (BABYLON) {
  89472. /**
  89473. * Single axis drag gizmo
  89474. */
  89475. var AxisDragGizmo = /** @class */ (function (_super) {
  89476. __extends(AxisDragGizmo, _super);
  89477. /**
  89478. * Creates an AxisDragGizmo
  89479. * @param gizmoLayer The utility layer the gizmo will be added to
  89480. * @param dragAxis The axis which the gizmo will be able to drag on
  89481. * @param color The color of the gizmo
  89482. */
  89483. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89484. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89485. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89486. var _this = _super.call(this, gizmoLayer) || this;
  89487. _this._pointerObserver = null;
  89488. /**
  89489. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89490. */
  89491. _this.snapDistance = 0;
  89492. /**
  89493. * Event that fires each time the gizmo snaps to a new location.
  89494. * * snapDistance is the the change in distance
  89495. */
  89496. _this.onSnapObservable = new BABYLON.Observable();
  89497. // Create Material
  89498. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89499. coloredMaterial.disableLighting = true;
  89500. coloredMaterial.emissiveColor = color;
  89501. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89502. hoverMaterial.disableLighting = true;
  89503. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89504. // Build mesh on root node
  89505. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89506. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89507. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89508. arrow.addChild(arrowMesh);
  89509. arrow.addChild(arrowTail);
  89510. // Position arrow pointing in its drag axis
  89511. arrowMesh.scaling.scaleInPlace(0.05);
  89512. arrowMesh.material = coloredMaterial;
  89513. arrowMesh.rotation.x = Math.PI / 2;
  89514. arrowMesh.position.z += 0.3;
  89515. arrowTail.rotation.x = Math.PI / 2;
  89516. arrowTail.material = coloredMaterial;
  89517. arrowTail.position.z += 0.15;
  89518. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89519. _this._rootMesh.addChild(arrow);
  89520. var currentSnapDragDistance = 0;
  89521. var tmpVector = new BABYLON.Vector3();
  89522. var tmpSnapEvent = { snapDistance: 0 };
  89523. // Add drag behavior to handle events when the gizmo is dragged
  89524. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89525. _this.dragBehavior.moveAttached = false;
  89526. _this._rootMesh.addBehavior(_this.dragBehavior);
  89527. _this.dragBehavior.onDragObservable.add(function (event) {
  89528. if (_this.attachedMesh) {
  89529. // Snapping logic
  89530. if (_this.snapDistance == 0) {
  89531. _this.attachedMesh.position.addInPlace(event.delta);
  89532. }
  89533. else {
  89534. currentSnapDragDistance += event.dragDistance;
  89535. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89536. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89537. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89538. event.delta.normalizeToRef(tmpVector);
  89539. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89540. _this.attachedMesh.position.addInPlace(tmpVector);
  89541. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89542. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89543. }
  89544. }
  89545. }
  89546. });
  89547. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89548. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89549. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89550. m.material = hoverMaterial;
  89551. });
  89552. }
  89553. else {
  89554. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89555. m.material = coloredMaterial;
  89556. });
  89557. }
  89558. });
  89559. return _this;
  89560. }
  89561. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89562. if (this.dragBehavior) {
  89563. this.dragBehavior.enabled = value ? true : false;
  89564. }
  89565. };
  89566. /**
  89567. * Disposes of the gizmo
  89568. */
  89569. AxisDragGizmo.prototype.dispose = function () {
  89570. this.onSnapObservable.clear();
  89571. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89572. this.dragBehavior.detach();
  89573. _super.prototype.dispose.call(this);
  89574. };
  89575. return AxisDragGizmo;
  89576. }(BABYLON.Gizmo));
  89577. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89578. })(BABYLON || (BABYLON = {}));
  89579. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89580. var BABYLON;
  89581. (function (BABYLON) {
  89582. /**
  89583. * Single axis scale gizmo
  89584. */
  89585. var AxisScaleGizmo = /** @class */ (function (_super) {
  89586. __extends(AxisScaleGizmo, _super);
  89587. /**
  89588. * Creates an AxisScaleGizmo
  89589. * @param gizmoLayer The utility layer the gizmo will be added to
  89590. * @param dragAxis The axis which the gizmo will be able to scale on
  89591. * @param color The color of the gizmo
  89592. */
  89593. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89594. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89595. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89596. var _this = _super.call(this, gizmoLayer) || this;
  89597. _this._pointerObserver = null;
  89598. /**
  89599. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89600. */
  89601. _this.snapDistance = 0;
  89602. /**
  89603. * Event that fires each time the gizmo snaps to a new location.
  89604. * * snapDistance is the the change in distance
  89605. */
  89606. _this.onSnapObservable = new BABYLON.Observable();
  89607. // Create Material
  89608. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89609. coloredMaterial.disableLighting = true;
  89610. coloredMaterial.emissiveColor = color;
  89611. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89612. hoverMaterial.disableLighting = true;
  89613. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89614. // Build mesh on root node
  89615. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89616. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89617. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89618. arrow.addChild(arrowMesh);
  89619. arrow.addChild(arrowTail);
  89620. // Position arrow pointing in its drag axis
  89621. arrowMesh.scaling.scaleInPlace(0.1);
  89622. arrowMesh.material = coloredMaterial;
  89623. arrowMesh.rotation.x = Math.PI / 2;
  89624. arrowMesh.position.z += 0.3;
  89625. arrowTail.rotation.x = Math.PI / 2;
  89626. arrowTail.material = coloredMaterial;
  89627. arrowTail.position.z += 0.15;
  89628. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89629. _this._rootMesh.addChild(arrow);
  89630. // Add drag behavior to handle events when the gizmo is dragged
  89631. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89632. _this.dragBehavior.moveAttached = false;
  89633. _this._rootMesh.addBehavior(_this.dragBehavior);
  89634. var currentSnapDragDistance = 0;
  89635. var tmpVector = new BABYLON.Vector3();
  89636. var tmpSnapEvent = { snapDistance: 0 };
  89637. _this.dragBehavior.onDragObservable.add(function (event) {
  89638. if (_this.attachedMesh) {
  89639. // Snapping logic
  89640. var snapped = false;
  89641. var dragSteps = 0;
  89642. if (_this.snapDistance == 0) {
  89643. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89644. }
  89645. else {
  89646. currentSnapDragDistance += event.dragDistance;
  89647. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89648. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89649. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89650. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89651. snapped = true;
  89652. }
  89653. else {
  89654. tmpVector.scaleInPlace(0);
  89655. }
  89656. }
  89657. var invertCount = 0;
  89658. if (_this.attachedMesh.scaling["x"] < 0) {
  89659. invertCount++;
  89660. }
  89661. if (_this.attachedMesh.scaling["y"] < 0) {
  89662. invertCount++;
  89663. }
  89664. if (_this.attachedMesh.scaling["z"] < 0) {
  89665. invertCount++;
  89666. }
  89667. if (invertCount % 2 == 0) {
  89668. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89669. }
  89670. else {
  89671. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  89672. }
  89673. if (snapped) {
  89674. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89675. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89676. }
  89677. }
  89678. });
  89679. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89680. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89681. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89682. m.material = hoverMaterial;
  89683. });
  89684. }
  89685. else {
  89686. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89687. m.material = coloredMaterial;
  89688. });
  89689. }
  89690. });
  89691. return _this;
  89692. }
  89693. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89694. if (this.dragBehavior) {
  89695. this.dragBehavior.enabled = value ? true : false;
  89696. }
  89697. };
  89698. /**
  89699. * Disposes of the gizmo
  89700. */
  89701. AxisScaleGizmo.prototype.dispose = function () {
  89702. this.onSnapObservable.clear();
  89703. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89704. this.dragBehavior.detach();
  89705. _super.prototype.dispose.call(this);
  89706. };
  89707. return AxisScaleGizmo;
  89708. }(BABYLON.Gizmo));
  89709. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89710. })(BABYLON || (BABYLON = {}));
  89711. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89712. var BABYLON;
  89713. (function (BABYLON) {
  89714. /**
  89715. * Single plane rotation gizmo
  89716. */
  89717. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89718. __extends(PlaneRotationGizmo, _super);
  89719. /**
  89720. * Creates a PlaneRotationGizmo
  89721. * @param gizmoLayer The utility layer the gizmo will be added to
  89722. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89723. * @param color The color of the gizmo
  89724. */
  89725. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89726. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89727. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89728. var _this = _super.call(this, gizmoLayer) || this;
  89729. _this._pointerObserver = null;
  89730. /**
  89731. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89732. */
  89733. _this.snapDistance = 0;
  89734. /**
  89735. * Event that fires each time the gizmo snaps to a new location.
  89736. * * snapDistance is the the change in distance
  89737. */
  89738. _this.onSnapObservable = new BABYLON.Observable();
  89739. // Create Material
  89740. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89741. coloredMaterial.disableLighting = true;
  89742. coloredMaterial.emissiveColor = color;
  89743. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89744. hoverMaterial.disableLighting = true;
  89745. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89746. // Build mesh on root node
  89747. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89748. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89749. // Position arrow pointing in its drag axis
  89750. rotationMesh.scaling.scaleInPlace(0.1);
  89751. rotationMesh.material = coloredMaterial;
  89752. rotationMesh.rotation.x = Math.PI / 2;
  89753. parentMesh.addChild(rotationMesh);
  89754. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89755. _this._rootMesh.addChild(parentMesh);
  89756. // Add drag behavior to handle events when the gizmo is dragged
  89757. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89758. _this.dragBehavior.moveAttached = false;
  89759. _this._rootMesh.addBehavior(_this.dragBehavior);
  89760. var lastDragPosition = null;
  89761. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89762. if (_this.attachedMesh) {
  89763. lastDragPosition = e.dragPlanePoint;
  89764. }
  89765. });
  89766. var rotationMatrix = new BABYLON.Matrix();
  89767. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89768. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89769. var tmpSnapEvent = { snapDistance: 0 };
  89770. var currentSnapDragDistance = 0;
  89771. _this.dragBehavior.onDragObservable.add(function (event) {
  89772. if (_this.attachedMesh && lastDragPosition) {
  89773. if (!_this.attachedMesh.rotationQuaternion) {
  89774. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  89775. }
  89776. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89777. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89778. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89779. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89780. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89781. var angle = Math.atan2(cross.length(), dot);
  89782. planeNormalTowardsCamera.copyFrom(planeNormal);
  89783. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89784. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89785. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89786. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89787. }
  89788. // Flip up vector depending on which side the camera is on
  89789. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89790. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89791. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89792. planeNormalTowardsCamera.scaleInPlace(-1);
  89793. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89794. }
  89795. }
  89796. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89797. if (halfCircleSide)
  89798. angle = -angle;
  89799. // Snapping logic
  89800. var snapped = false;
  89801. if (_this.snapDistance != 0) {
  89802. currentSnapDragDistance += angle;
  89803. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89804. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89805. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89806. angle = _this.snapDistance * dragSteps;
  89807. snapped = true;
  89808. }
  89809. else {
  89810. angle = 0;
  89811. }
  89812. }
  89813. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89814. var quaternionCoefficient = Math.sin(angle / 2);
  89815. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89816. // Rotate selected mesh quaternion over fixed axis
  89817. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89818. lastDragPosition = event.dragPlanePoint;
  89819. if (snapped) {
  89820. tmpSnapEvent.snapDistance = angle;
  89821. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89822. }
  89823. }
  89824. });
  89825. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89826. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89827. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89828. m.material = hoverMaterial;
  89829. });
  89830. }
  89831. else {
  89832. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89833. m.material = coloredMaterial;
  89834. });
  89835. }
  89836. });
  89837. return _this;
  89838. }
  89839. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89840. if (this.dragBehavior) {
  89841. this.dragBehavior.enabled = value ? true : false;
  89842. }
  89843. };
  89844. /**
  89845. * Disposes of the gizmo
  89846. */
  89847. PlaneRotationGizmo.prototype.dispose = function () {
  89848. this.onSnapObservable.clear();
  89849. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89850. this.dragBehavior.detach();
  89851. _super.prototype.dispose.call(this);
  89852. };
  89853. return PlaneRotationGizmo;
  89854. }(BABYLON.Gizmo));
  89855. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89856. })(BABYLON || (BABYLON = {}));
  89857. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89858. var BABYLON;
  89859. (function (BABYLON) {
  89860. /**
  89861. * Gizmo that enables dragging a mesh along 3 axis
  89862. */
  89863. var PositionGizmo = /** @class */ (function (_super) {
  89864. __extends(PositionGizmo, _super);
  89865. /**
  89866. * Creates a PositionGizmo
  89867. * @param gizmoLayer The utility layer the gizmo will be added to
  89868. */
  89869. function PositionGizmo(gizmoLayer) {
  89870. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89871. var _this = _super.call(this, gizmoLayer) || this;
  89872. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89873. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89874. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89875. _this.attachedMesh = null;
  89876. return _this;
  89877. }
  89878. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89879. set: function (mesh) {
  89880. if (this.xGizmo) {
  89881. this.xGizmo.attachedMesh = mesh;
  89882. this.yGizmo.attachedMesh = mesh;
  89883. this.zGizmo.attachedMesh = mesh;
  89884. }
  89885. },
  89886. enumerable: true,
  89887. configurable: true
  89888. });
  89889. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89890. get: function () {
  89891. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89892. },
  89893. set: function (value) {
  89894. if (this.xGizmo) {
  89895. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89896. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89897. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89898. }
  89899. },
  89900. enumerable: true,
  89901. configurable: true
  89902. });
  89903. /**
  89904. * Disposes of the gizmo
  89905. */
  89906. PositionGizmo.prototype.dispose = function () {
  89907. this.xGizmo.dispose();
  89908. this.yGizmo.dispose();
  89909. this.zGizmo.dispose();
  89910. };
  89911. return PositionGizmo;
  89912. }(BABYLON.Gizmo));
  89913. BABYLON.PositionGizmo = PositionGizmo;
  89914. })(BABYLON || (BABYLON = {}));
  89915. //# sourceMappingURL=babylon.positionGizmo.js.map
  89916. var BABYLON;
  89917. (function (BABYLON) {
  89918. /**
  89919. * Gizmo that enables rotating a mesh along 3 axis
  89920. */
  89921. var RotationGizmo = /** @class */ (function (_super) {
  89922. __extends(RotationGizmo, _super);
  89923. /**
  89924. * Creates a RotationGizmo
  89925. * @param gizmoLayer The utility layer the gizmo will be added to
  89926. */
  89927. function RotationGizmo(gizmoLayer) {
  89928. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89929. var _this = _super.call(this, gizmoLayer) || this;
  89930. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89931. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89932. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89933. _this.attachedMesh = null;
  89934. return _this;
  89935. }
  89936. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89937. set: function (mesh) {
  89938. if (this.xGizmo) {
  89939. this.xGizmo.attachedMesh = mesh;
  89940. this.yGizmo.attachedMesh = mesh;
  89941. this.zGizmo.attachedMesh = mesh;
  89942. }
  89943. },
  89944. enumerable: true,
  89945. configurable: true
  89946. });
  89947. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89948. get: function () {
  89949. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89950. },
  89951. set: function (value) {
  89952. if (this.xGizmo) {
  89953. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89954. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89955. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89956. }
  89957. },
  89958. enumerable: true,
  89959. configurable: true
  89960. });
  89961. /**
  89962. * Disposes of the gizmo
  89963. */
  89964. RotationGizmo.prototype.dispose = function () {
  89965. this.xGizmo.dispose();
  89966. this.yGizmo.dispose();
  89967. this.zGizmo.dispose();
  89968. };
  89969. return RotationGizmo;
  89970. }(BABYLON.Gizmo));
  89971. BABYLON.RotationGizmo = RotationGizmo;
  89972. })(BABYLON || (BABYLON = {}));
  89973. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89974. var BABYLON;
  89975. (function (BABYLON) {
  89976. /**
  89977. * Gizmo that enables scaling a mesh along 3 axis
  89978. */
  89979. var ScaleGizmo = /** @class */ (function (_super) {
  89980. __extends(ScaleGizmo, _super);
  89981. /**
  89982. * Creates a ScaleGizmo
  89983. * @param gizmoLayer The utility layer the gizmo will be added to
  89984. */
  89985. function ScaleGizmo(gizmoLayer) {
  89986. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89987. var _this = _super.call(this, gizmoLayer) || this;
  89988. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89989. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89990. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89991. _this.attachedMesh = null;
  89992. return _this;
  89993. }
  89994. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89995. set: function (mesh) {
  89996. if (this.xGizmo) {
  89997. this.xGizmo.attachedMesh = mesh;
  89998. this.yGizmo.attachedMesh = mesh;
  89999. this.zGizmo.attachedMesh = mesh;
  90000. }
  90001. },
  90002. enumerable: true,
  90003. configurable: true
  90004. });
  90005. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90006. get: function () {
  90007. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90008. },
  90009. set: function (value) {
  90010. if (this.xGizmo) {
  90011. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90012. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90013. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90014. }
  90015. },
  90016. enumerable: true,
  90017. configurable: true
  90018. });
  90019. /**
  90020. * Disposes of the gizmo
  90021. */
  90022. ScaleGizmo.prototype.dispose = function () {
  90023. this.xGizmo.dispose();
  90024. this.yGizmo.dispose();
  90025. this.zGizmo.dispose();
  90026. };
  90027. return ScaleGizmo;
  90028. }(BABYLON.Gizmo));
  90029. BABYLON.ScaleGizmo = ScaleGizmo;
  90030. })(BABYLON || (BABYLON = {}));
  90031. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90032. var BABYLON;
  90033. (function (BABYLON) {
  90034. /**
  90035. * Bounding box gizmo
  90036. */
  90037. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90038. __extends(BoundingBoxGizmo, _super);
  90039. /**
  90040. * Creates an BoundingBoxGizmo
  90041. * @param gizmoLayer The utility layer the gizmo will be added to
  90042. * @param color The color of the gizmo
  90043. */
  90044. function BoundingBoxGizmo(color, gizmoLayer) {
  90045. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90046. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90047. var _this = _super.call(this, gizmoLayer) || this;
  90048. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90049. _this._renderObserver = null;
  90050. _this._pointerObserver = null;
  90051. _this._scaleDragSpeed = 0.2;
  90052. _this._tmpQuaternion = new BABYLON.Quaternion();
  90053. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90054. /**
  90055. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90056. */
  90057. _this.rotationSphereSize = 0.1;
  90058. /**
  90059. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90060. */
  90061. _this.scaleBoxSize = 0.1;
  90062. /**
  90063. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  90064. */
  90065. _this.fixedDragMeshScreenSize = false;
  90066. /**
  90067. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90068. */
  90069. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90070. /**
  90071. * Fired when a rotation sphere or scale box is dragged
  90072. */
  90073. _this.onDragStartObservable = new BABYLON.Observable();
  90074. /**
  90075. * Fired when a rotation sphere or scale box drag is started
  90076. */
  90077. _this.onDragObservable = new BABYLON.Observable();
  90078. /**
  90079. * Fired when a rotation sphere or scale box drag is needed
  90080. */
  90081. _this.onDragEndObservable = new BABYLON.Observable();
  90082. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90083. _this._updateScale = false;
  90084. // Create Materials
  90085. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90086. coloredMaterial.disableLighting = true;
  90087. coloredMaterial.emissiveColor = color;
  90088. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90089. hoverColoredMaterial.disableLighting = true;
  90090. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90091. // Build bounding box out of lines
  90092. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90093. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90094. var lines = [];
  90095. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90096. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90097. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90098. 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));
  90099. 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));
  90100. 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));
  90101. 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));
  90102. 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));
  90103. 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));
  90104. 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));
  90105. 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));
  90106. 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));
  90107. lines.forEach(function (l) {
  90108. l.color = color;
  90109. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90110. l.isPickable = false;
  90111. _this._lineBoundingBox.addChild(l);
  90112. });
  90113. _this._rootMesh.addChild(_this._lineBoundingBox);
  90114. // Create rotation spheres
  90115. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90116. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90117. var _loop_1 = function (i_1) {
  90118. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90119. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90120. sphere.material = coloredMaterial;
  90121. // Drag behavior
  90122. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90123. _dragBehavior.moveAttached = false;
  90124. _dragBehavior.updateDragPlane = false;
  90125. sphere.addBehavior(_dragBehavior);
  90126. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90127. var totalTurnAmountOfDrag = 0;
  90128. _dragBehavior.onDragStartObservable.add(function (event) {
  90129. startingTurnDirection.copyFrom(sphere.forward);
  90130. totalTurnAmountOfDrag = 0;
  90131. });
  90132. _dragBehavior.onDragObservable.add(function (event) {
  90133. _this.onDragObservable.notifyObservers({});
  90134. if (_this.attachedMesh) {
  90135. var worldDragDirection = startingTurnDirection;
  90136. // Project the world right on to the drag plane
  90137. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90138. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90139. // project drag delta on to the resulting drag axis and rotate based on that
  90140. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90141. // Rotate based on axis
  90142. if (!_this.attachedMesh.rotationQuaternion) {
  90143. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90144. }
  90145. // Do not allow the object to turn more than a full circle
  90146. totalTurnAmountOfDrag += projectDist;
  90147. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90148. if (i_1 >= 8) {
  90149. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90150. }
  90151. else if (i_1 >= 4) {
  90152. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90153. }
  90154. else {
  90155. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90156. }
  90157. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  90158. }
  90159. }
  90160. });
  90161. // Selection/deselection
  90162. _dragBehavior.onDragStartObservable.add(function () {
  90163. _this.onDragStartObservable.notifyObservers({});
  90164. _this._selectNode(sphere);
  90165. });
  90166. _dragBehavior.onDragEndObservable.add(function () {
  90167. _this.onDragEndObservable.notifyObservers({});
  90168. _this._selectNode(null);
  90169. });
  90170. this_1._rotateSpheresParent.addChild(sphere);
  90171. };
  90172. var this_1 = this, _dragBehavior;
  90173. for (var i_1 = 0; i_1 < 12; i_1++) {
  90174. _loop_1(i_1);
  90175. }
  90176. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90177. // Create scale cubes
  90178. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90179. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90180. for (var i = 0; i < 2; i++) {
  90181. for (var j = 0; j < 2; j++) {
  90182. var _loop_2 = function () {
  90183. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90184. box.material = coloredMaterial;
  90185. // Dragging logic
  90186. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90187. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90188. _dragBehavior.moveAttached = false;
  90189. box.addBehavior(_dragBehavior);
  90190. _dragBehavior.onDragObservable.add(function (event) {
  90191. _this.onDragObservable.notifyObservers({});
  90192. if (_this.attachedMesh) {
  90193. // Current boudning box dimensions
  90194. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  90195. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  90196. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  90197. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90198. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90199. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  90200. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  90201. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  90202. // Update scale and position
  90203. _this.attachedMesh.scaling.addInPlace(deltaScale);
  90204. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  90205. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  90206. }
  90207. });
  90208. // Selection/deselection
  90209. _dragBehavior.onDragStartObservable.add(function () {
  90210. _this.onDragStartObservable.notifyObservers({});
  90211. _this._selectNode(box);
  90212. });
  90213. _dragBehavior.onDragEndObservable.add(function () {
  90214. _this.onDragEndObservable.notifyObservers({});
  90215. _this._selectNode(null);
  90216. });
  90217. this_2._scaleBoxesParent.addChild(box);
  90218. };
  90219. var this_2 = this, _dragBehavior;
  90220. for (var k = 0; k < 2; k++) {
  90221. _loop_2();
  90222. }
  90223. }
  90224. }
  90225. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90226. // Hover color change
  90227. var pointerIds = new Array();
  90228. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90229. if (!pointerIds[pointerInfo.event.pointerId]) {
  90230. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90231. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90232. pointerIds[pointerInfo.event.pointerId] = mesh;
  90233. mesh.material = hoverColoredMaterial;
  90234. }
  90235. });
  90236. }
  90237. else {
  90238. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90239. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90240. delete pointerIds[pointerInfo.event.pointerId];
  90241. }
  90242. }
  90243. });
  90244. // Update bounding box positions
  90245. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90246. _this._updateBoundingBox();
  90247. });
  90248. _this._updateBoundingBox();
  90249. return _this;
  90250. }
  90251. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90252. this._rotateSpheresParent.getChildMeshes()
  90253. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90254. m.isVisible = (!selectedMesh || m == selectedMesh);
  90255. });
  90256. };
  90257. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90258. if (this.attachedMesh) {
  90259. // Update bounding dimensions/positions
  90260. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  90261. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  90262. this._boundingDimensions.copyFrom(boundBoxDimensions);
  90263. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90264. }
  90265. // Update rotation sphere locations
  90266. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90267. for (var i = 0; i < 3; i++) {
  90268. for (var j = 0; j < 2; j++) {
  90269. for (var k = 0; k < 2; k++) {
  90270. var index = ((i * 4) + (j * 2)) + k;
  90271. if (i == 0) {
  90272. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90273. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90274. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90275. }
  90276. if (i == 1) {
  90277. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90278. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90279. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90280. }
  90281. if (i == 2) {
  90282. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90283. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90284. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90285. }
  90286. if (this.fixedDragMeshScreenSize) {
  90287. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90288. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90289. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90290. }
  90291. else {
  90292. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90293. }
  90294. }
  90295. }
  90296. }
  90297. // Update scale box locations
  90298. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90299. for (var i = 0; i < 2; i++) {
  90300. for (var j = 0; j < 2; j++) {
  90301. for (var k = 0; k < 2; k++) {
  90302. var index = ((i * 4) + (j * 2)) + k;
  90303. if (scaleBoxes[index]) {
  90304. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90305. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90306. if (this.fixedDragMeshScreenSize) {
  90307. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90308. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90309. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90310. }
  90311. else {
  90312. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90313. }
  90314. }
  90315. }
  90316. }
  90317. }
  90318. };
  90319. /**
  90320. * Enables rotation on the specified axis and disables rotation on the others
  90321. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90322. */
  90323. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90324. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90325. if (i < 4) {
  90326. m.setEnabled(axis.indexOf("x") != -1);
  90327. }
  90328. else if (i < 8) {
  90329. m.setEnabled(axis.indexOf("y") != -1);
  90330. }
  90331. else {
  90332. m.setEnabled(axis.indexOf("z") != -1);
  90333. }
  90334. });
  90335. };
  90336. /**
  90337. * Disposes of the gizmo
  90338. */
  90339. BoundingBoxGizmo.prototype.dispose = function () {
  90340. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90341. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90342. this._lineBoundingBox.dispose();
  90343. this._rotateSpheresParent.dispose();
  90344. this._scaleBoxesParent.dispose();
  90345. _super.prototype.dispose.call(this);
  90346. };
  90347. return BoundingBoxGizmo;
  90348. }(BABYLON.Gizmo));
  90349. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90350. })(BABYLON || (BABYLON = {}));
  90351. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90352. var BABYLON;
  90353. (function (BABYLON) {
  90354. /**
  90355. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90356. */
  90357. var GizmoManager = /** @class */ (function () {
  90358. /**
  90359. * Instatiates a gizmo manager
  90360. * @param scene the scene to overlay the gizmos on top of
  90361. * @param options If only a single gizmo should exist at one time
  90362. */
  90363. function GizmoManager(scene, options) {
  90364. var _this = this;
  90365. this.scene = scene;
  90366. // Set of gizmos that are currently in the scene for each mesh
  90367. this._gizmoSet = {};
  90368. this._pointerObserver = null;
  90369. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  90370. // Options parsing
  90371. if (!options) {
  90372. options = {};
  90373. }
  90374. if (options.singleGizmo === undefined) {
  90375. options.singleGizmo = true;
  90376. }
  90377. // Instatiate/dispose gizmos based on pointer actions
  90378. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90379. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90380. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90381. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  90382. if (options.singleGizmo) {
  90383. _this._clearGizmos();
  90384. }
  90385. // Enable gizmo when mesh is selected
  90386. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  90387. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90388. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90389. }
  90390. else {
  90391. if (!options.singleGizmo) {
  90392. // Disable gizmo when clicked again
  90393. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  90394. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  90395. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  90396. }
  90397. }
  90398. }
  90399. else {
  90400. if (options.singleGizmo) {
  90401. // Disable gizmo when clicked away
  90402. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90403. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  90404. if (gizmoPick && !gizmoPick.hit) {
  90405. _this._clearGizmos();
  90406. }
  90407. }
  90408. }
  90409. }
  90410. }
  90411. });
  90412. }
  90413. /**
  90414. * Disposes of the gizmo manager
  90415. */
  90416. GizmoManager.prototype.dispose = function () {
  90417. this.scene.onPointerObservable.remove(this._pointerObserver);
  90418. this._clearGizmos();
  90419. this._gizmoLayer.dispose();
  90420. };
  90421. GizmoManager.prototype._clearGizmos = function () {
  90422. for (var key in this._gizmoSet) {
  90423. if (this._gizmoSet.hasOwnProperty(key)) {
  90424. this._gizmoSet[key].positionGizmo.dispose();
  90425. this._gizmoSet[key].rotationGizmo.dispose();
  90426. delete this._gizmoSet[key];
  90427. }
  90428. }
  90429. };
  90430. return GizmoManager;
  90431. }());
  90432. BABYLON.GizmoManager = GizmoManager;
  90433. })(BABYLON || (BABYLON = {}));
  90434. //# sourceMappingURL=babylon.gizmoManager.js.map
  90435. var BABYLON;
  90436. (function (BABYLON) {
  90437. /**
  90438. * Defines a target to use with MorphTargetManager
  90439. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90440. */
  90441. var MorphTarget = /** @class */ (function () {
  90442. /**
  90443. * Creates a new MorphTarget
  90444. * @param name defines the name of the target
  90445. * @param influence defines the influence to use
  90446. */
  90447. function MorphTarget(
  90448. /** defines the name of the target */
  90449. name, influence, scene) {
  90450. if (influence === void 0) { influence = 0; }
  90451. if (scene === void 0) { scene = null; }
  90452. this.name = name;
  90453. /**
  90454. * Gets or sets the list of animations
  90455. */
  90456. this.animations = new Array();
  90457. this._positions = null;
  90458. this._normals = null;
  90459. this._tangents = null;
  90460. /**
  90461. * Observable raised when the influence changes
  90462. */
  90463. this.onInfluenceChanged = new BABYLON.Observable();
  90464. this._animationPropertiesOverride = null;
  90465. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90466. this.influence = influence;
  90467. }
  90468. Object.defineProperty(MorphTarget.prototype, "influence", {
  90469. /**
  90470. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90471. */
  90472. get: function () {
  90473. return this._influence;
  90474. },
  90475. set: function (influence) {
  90476. if (this._influence === influence) {
  90477. return;
  90478. }
  90479. var previous = this._influence;
  90480. this._influence = influence;
  90481. if (this.onInfluenceChanged.hasObservers) {
  90482. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90483. }
  90484. },
  90485. enumerable: true,
  90486. configurable: true
  90487. });
  90488. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90489. /**
  90490. * Gets or sets the animation properties override
  90491. */
  90492. get: function () {
  90493. if (!this._animationPropertiesOverride && this._scene) {
  90494. return this._scene.animationPropertiesOverride;
  90495. }
  90496. return this._animationPropertiesOverride;
  90497. },
  90498. set: function (value) {
  90499. this._animationPropertiesOverride = value;
  90500. },
  90501. enumerable: true,
  90502. configurable: true
  90503. });
  90504. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90505. /**
  90506. * Gets a boolean defining if the target contains position data
  90507. */
  90508. get: function () {
  90509. return !!this._positions;
  90510. },
  90511. enumerable: true,
  90512. configurable: true
  90513. });
  90514. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90515. /**
  90516. * Gets a boolean defining if the target contains normal data
  90517. */
  90518. get: function () {
  90519. return !!this._normals;
  90520. },
  90521. enumerable: true,
  90522. configurable: true
  90523. });
  90524. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90525. /**
  90526. * Gets a boolean defining if the target contains tangent data
  90527. */
  90528. get: function () {
  90529. return !!this._tangents;
  90530. },
  90531. enumerable: true,
  90532. configurable: true
  90533. });
  90534. /**
  90535. * Affects position data to this target
  90536. * @param data defines the position data to use
  90537. */
  90538. MorphTarget.prototype.setPositions = function (data) {
  90539. this._positions = data;
  90540. };
  90541. /**
  90542. * Gets the position data stored in this target
  90543. * @returns a FloatArray containing the position data (or null if not present)
  90544. */
  90545. MorphTarget.prototype.getPositions = function () {
  90546. return this._positions;
  90547. };
  90548. /**
  90549. * Affects normal data to this target
  90550. * @param data defines the normal data to use
  90551. */
  90552. MorphTarget.prototype.setNormals = function (data) {
  90553. this._normals = data;
  90554. };
  90555. /**
  90556. * Gets the normal data stored in this target
  90557. * @returns a FloatArray containing the normal data (or null if not present)
  90558. */
  90559. MorphTarget.prototype.getNormals = function () {
  90560. return this._normals;
  90561. };
  90562. /**
  90563. * Affects tangent data to this target
  90564. * @param data defines the tangent data to use
  90565. */
  90566. MorphTarget.prototype.setTangents = function (data) {
  90567. this._tangents = data;
  90568. };
  90569. /**
  90570. * Gets the tangent data stored in this target
  90571. * @returns a FloatArray containing the tangent data (or null if not present)
  90572. */
  90573. MorphTarget.prototype.getTangents = function () {
  90574. return this._tangents;
  90575. };
  90576. /**
  90577. * Serializes the current target into a Serialization object
  90578. * @returns the serialized object
  90579. */
  90580. MorphTarget.prototype.serialize = function () {
  90581. var serializationObject = {};
  90582. serializationObject.name = this.name;
  90583. serializationObject.influence = this.influence;
  90584. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90585. if (this.hasNormals) {
  90586. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90587. }
  90588. if (this.hasTangents) {
  90589. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90590. }
  90591. // Animations
  90592. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90593. return serializationObject;
  90594. };
  90595. // Statics
  90596. /**
  90597. * Creates a new target from serialized data
  90598. * @param serializationObject defines the serialized data to use
  90599. * @returns a new MorphTarget
  90600. */
  90601. MorphTarget.Parse = function (serializationObject) {
  90602. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90603. result.setPositions(serializationObject.positions);
  90604. if (serializationObject.normals) {
  90605. result.setNormals(serializationObject.normals);
  90606. }
  90607. if (serializationObject.tangents) {
  90608. result.setTangents(serializationObject.tangents);
  90609. }
  90610. // Animations
  90611. if (serializationObject.animations) {
  90612. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90613. var parsedAnimation = serializationObject.animations[animationIndex];
  90614. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90615. }
  90616. }
  90617. return result;
  90618. };
  90619. /**
  90620. * Creates a MorphTarget from mesh data
  90621. * @param mesh defines the source mesh
  90622. * @param name defines the name to use for the new target
  90623. * @param influence defines the influence to attach to the target
  90624. * @returns a new MorphTarget
  90625. */
  90626. MorphTarget.FromMesh = function (mesh, name, influence) {
  90627. if (!name) {
  90628. name = mesh.name;
  90629. }
  90630. var result = new MorphTarget(name, influence, mesh.getScene());
  90631. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90633. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90634. }
  90635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90636. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90637. }
  90638. return result;
  90639. };
  90640. return MorphTarget;
  90641. }());
  90642. BABYLON.MorphTarget = MorphTarget;
  90643. })(BABYLON || (BABYLON = {}));
  90644. //# sourceMappingURL=babylon.morphTarget.js.map
  90645. var BABYLON;
  90646. (function (BABYLON) {
  90647. /**
  90648. * This class is used to deform meshes using morphing between different targets
  90649. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90650. */
  90651. var MorphTargetManager = /** @class */ (function () {
  90652. /**
  90653. * Creates a new MorphTargetManager
  90654. * @param scene defines the current scene
  90655. */
  90656. function MorphTargetManager(scene) {
  90657. if (scene === void 0) { scene = null; }
  90658. this._targets = new Array();
  90659. this._targetObservable = new Array();
  90660. this._activeTargets = new BABYLON.SmartArray(16);
  90661. this._supportsNormals = false;
  90662. this._supportsTangents = false;
  90663. this._vertexCount = 0;
  90664. this._uniqueId = 0;
  90665. this._tempInfluences = new Array();
  90666. if (!scene) {
  90667. scene = BABYLON.Engine.LastCreatedScene;
  90668. }
  90669. this._scene = scene;
  90670. if (this._scene) {
  90671. this._scene.morphTargetManagers.push(this);
  90672. this._uniqueId = this._scene.getUniqueId();
  90673. }
  90674. }
  90675. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90676. /**
  90677. * Gets the unique ID of this manager
  90678. */
  90679. get: function () {
  90680. return this._uniqueId;
  90681. },
  90682. enumerable: true,
  90683. configurable: true
  90684. });
  90685. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90686. /**
  90687. * Gets the number of vertices handled by this manager
  90688. */
  90689. get: function () {
  90690. return this._vertexCount;
  90691. },
  90692. enumerable: true,
  90693. configurable: true
  90694. });
  90695. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90696. /**
  90697. * Gets a boolean indicating if this manager supports morphing of normals
  90698. */
  90699. get: function () {
  90700. return this._supportsNormals;
  90701. },
  90702. enumerable: true,
  90703. configurable: true
  90704. });
  90705. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90706. /**
  90707. * Gets a boolean indicating if this manager supports morphing of tangents
  90708. */
  90709. get: function () {
  90710. return this._supportsTangents;
  90711. },
  90712. enumerable: true,
  90713. configurable: true
  90714. });
  90715. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90716. /**
  90717. * Gets the number of targets stored in this manager
  90718. */
  90719. get: function () {
  90720. return this._targets.length;
  90721. },
  90722. enumerable: true,
  90723. configurable: true
  90724. });
  90725. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90726. /**
  90727. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90728. */
  90729. get: function () {
  90730. return this._activeTargets.length;
  90731. },
  90732. enumerable: true,
  90733. configurable: true
  90734. });
  90735. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90736. /**
  90737. * Gets the list of influences (one per target)
  90738. */
  90739. get: function () {
  90740. return this._influences;
  90741. },
  90742. enumerable: true,
  90743. configurable: true
  90744. });
  90745. /**
  90746. * Gets the active target at specified index. An active target is a target with an influence > 0
  90747. * @param index defines the index to check
  90748. * @returns the requested target
  90749. */
  90750. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90751. return this._activeTargets.data[index];
  90752. };
  90753. /**
  90754. * Gets the target at specified index
  90755. * @param index defines the index to check
  90756. * @returns the requested target
  90757. */
  90758. MorphTargetManager.prototype.getTarget = function (index) {
  90759. return this._targets[index];
  90760. };
  90761. /**
  90762. * Add a new target to this manager
  90763. * @param target defines the target to add
  90764. */
  90765. MorphTargetManager.prototype.addTarget = function (target) {
  90766. var _this = this;
  90767. this._targets.push(target);
  90768. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90769. _this._syncActiveTargets(needUpdate);
  90770. }));
  90771. this._syncActiveTargets(true);
  90772. };
  90773. /**
  90774. * Removes a target from the manager
  90775. * @param target defines the target to remove
  90776. */
  90777. MorphTargetManager.prototype.removeTarget = function (target) {
  90778. var index = this._targets.indexOf(target);
  90779. if (index >= 0) {
  90780. this._targets.splice(index, 1);
  90781. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90782. this._syncActiveTargets(true);
  90783. }
  90784. };
  90785. /**
  90786. * Serializes the current manager into a Serialization object
  90787. * @returns the serialized object
  90788. */
  90789. MorphTargetManager.prototype.serialize = function () {
  90790. var serializationObject = {};
  90791. serializationObject.id = this.uniqueId;
  90792. serializationObject.targets = [];
  90793. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90794. var target = _a[_i];
  90795. serializationObject.targets.push(target.serialize());
  90796. }
  90797. return serializationObject;
  90798. };
  90799. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90800. var influenceCount = 0;
  90801. this._activeTargets.reset();
  90802. this._supportsNormals = true;
  90803. this._supportsTangents = true;
  90804. this._vertexCount = 0;
  90805. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90806. var target = _a[_i];
  90807. this._activeTargets.push(target);
  90808. this._tempInfluences[influenceCount++] = target.influence;
  90809. var positions = target.getPositions();
  90810. if (positions) {
  90811. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90812. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90813. var vertexCount = positions.length / 3;
  90814. if (this._vertexCount === 0) {
  90815. this._vertexCount = vertexCount;
  90816. }
  90817. else if (this._vertexCount !== vertexCount) {
  90818. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90819. return;
  90820. }
  90821. }
  90822. }
  90823. if (!this._influences || this._influences.length !== influenceCount) {
  90824. this._influences = new Float32Array(influenceCount);
  90825. }
  90826. for (var index = 0; index < influenceCount; index++) {
  90827. this._influences[index] = this._tempInfluences[index];
  90828. }
  90829. if (needUpdate) {
  90830. this.synchronize();
  90831. }
  90832. };
  90833. /**
  90834. * Syncrhonize the targets with all the meshes using this morph target manager
  90835. */
  90836. MorphTargetManager.prototype.synchronize = function () {
  90837. if (!this._scene) {
  90838. return;
  90839. }
  90840. // Flag meshes as dirty to resync with the active targets
  90841. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90842. var mesh = _a[_i];
  90843. if (mesh.morphTargetManager === this) {
  90844. mesh._syncGeometryWithMorphTargetManager();
  90845. }
  90846. }
  90847. };
  90848. // Statics
  90849. /**
  90850. * Creates a new MorphTargetManager from serialized data
  90851. * @param serializationObject defines the serialized data
  90852. * @param scene defines the hosting scene
  90853. * @returns the new MorphTargetManager
  90854. */
  90855. MorphTargetManager.Parse = function (serializationObject, scene) {
  90856. var result = new MorphTargetManager(scene);
  90857. result._uniqueId = serializationObject.id;
  90858. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90859. var targetData = _a[_i];
  90860. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90861. }
  90862. return result;
  90863. };
  90864. return MorphTargetManager;
  90865. }());
  90866. BABYLON.MorphTargetManager = MorphTargetManager;
  90867. })(BABYLON || (BABYLON = {}));
  90868. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90869. var BABYLON;
  90870. (function (BABYLON) {
  90871. var Octree = /** @class */ (function () {
  90872. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90873. if (maxDepth === void 0) { maxDepth = 2; }
  90874. this.maxDepth = maxDepth;
  90875. this.dynamicContent = new Array();
  90876. this._maxBlockCapacity = maxBlockCapacity || 64;
  90877. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90878. this._creationFunc = creationFunc;
  90879. }
  90880. // Methods
  90881. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90882. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90883. };
  90884. Octree.prototype.addMesh = function (entry) {
  90885. for (var index = 0; index < this.blocks.length; index++) {
  90886. var block = this.blocks[index];
  90887. block.addEntry(entry);
  90888. }
  90889. };
  90890. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90891. this._selectionContent.reset();
  90892. for (var index = 0; index < this.blocks.length; index++) {
  90893. var block = this.blocks[index];
  90894. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90895. }
  90896. if (allowDuplicate) {
  90897. this._selectionContent.concat(this.dynamicContent);
  90898. }
  90899. else {
  90900. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90901. }
  90902. return this._selectionContent;
  90903. };
  90904. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90905. this._selectionContent.reset();
  90906. for (var index = 0; index < this.blocks.length; index++) {
  90907. var block = this.blocks[index];
  90908. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90909. }
  90910. if (allowDuplicate) {
  90911. this._selectionContent.concat(this.dynamicContent);
  90912. }
  90913. else {
  90914. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90915. }
  90916. return this._selectionContent;
  90917. };
  90918. Octree.prototype.intersectsRay = function (ray) {
  90919. this._selectionContent.reset();
  90920. for (var index = 0; index < this.blocks.length; index++) {
  90921. var block = this.blocks[index];
  90922. block.intersectsRay(ray, this._selectionContent);
  90923. }
  90924. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90925. return this._selectionContent;
  90926. };
  90927. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90928. target.blocks = new Array();
  90929. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90930. // Segmenting space
  90931. for (var x = 0; x < 2; x++) {
  90932. for (var y = 0; y < 2; y++) {
  90933. for (var z = 0; z < 2; z++) {
  90934. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90935. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90936. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90937. block.addEntries(entries);
  90938. target.blocks.push(block);
  90939. }
  90940. }
  90941. }
  90942. };
  90943. Octree.CreationFuncForMeshes = function (entry, block) {
  90944. var boundingInfo = entry.getBoundingInfo();
  90945. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90946. block.entries.push(entry);
  90947. }
  90948. };
  90949. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90950. var boundingInfo = entry.getBoundingInfo();
  90951. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90952. block.entries.push(entry);
  90953. }
  90954. };
  90955. return Octree;
  90956. }());
  90957. BABYLON.Octree = Octree;
  90958. })(BABYLON || (BABYLON = {}));
  90959. //# sourceMappingURL=babylon.octree.js.map
  90960. var BABYLON;
  90961. (function (BABYLON) {
  90962. var OctreeBlock = /** @class */ (function () {
  90963. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90964. this.entries = new Array();
  90965. this._boundingVectors = new Array();
  90966. this._capacity = capacity;
  90967. this._depth = depth;
  90968. this._maxDepth = maxDepth;
  90969. this._creationFunc = creationFunc;
  90970. this._minPoint = minPoint;
  90971. this._maxPoint = maxPoint;
  90972. this._boundingVectors.push(minPoint.clone());
  90973. this._boundingVectors.push(maxPoint.clone());
  90974. this._boundingVectors.push(minPoint.clone());
  90975. this._boundingVectors[2].x = maxPoint.x;
  90976. this._boundingVectors.push(minPoint.clone());
  90977. this._boundingVectors[3].y = maxPoint.y;
  90978. this._boundingVectors.push(minPoint.clone());
  90979. this._boundingVectors[4].z = maxPoint.z;
  90980. this._boundingVectors.push(maxPoint.clone());
  90981. this._boundingVectors[5].z = minPoint.z;
  90982. this._boundingVectors.push(maxPoint.clone());
  90983. this._boundingVectors[6].x = minPoint.x;
  90984. this._boundingVectors.push(maxPoint.clone());
  90985. this._boundingVectors[7].y = minPoint.y;
  90986. }
  90987. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  90988. // Property
  90989. get: function () {
  90990. return this._capacity;
  90991. },
  90992. enumerable: true,
  90993. configurable: true
  90994. });
  90995. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  90996. get: function () {
  90997. return this._minPoint;
  90998. },
  90999. enumerable: true,
  91000. configurable: true
  91001. });
  91002. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91003. get: function () {
  91004. return this._maxPoint;
  91005. },
  91006. enumerable: true,
  91007. configurable: true
  91008. });
  91009. // Methods
  91010. OctreeBlock.prototype.addEntry = function (entry) {
  91011. if (this.blocks) {
  91012. for (var index = 0; index < this.blocks.length; index++) {
  91013. var block = this.blocks[index];
  91014. block.addEntry(entry);
  91015. }
  91016. return;
  91017. }
  91018. this._creationFunc(entry, this);
  91019. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91020. this.createInnerBlocks();
  91021. }
  91022. };
  91023. OctreeBlock.prototype.addEntries = function (entries) {
  91024. for (var index = 0; index < entries.length; index++) {
  91025. var mesh = entries[index];
  91026. this.addEntry(mesh);
  91027. }
  91028. };
  91029. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91030. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91031. if (this.blocks) {
  91032. for (var index = 0; index < this.blocks.length; index++) {
  91033. var block = this.blocks[index];
  91034. block.select(frustumPlanes, selection, allowDuplicate);
  91035. }
  91036. return;
  91037. }
  91038. if (allowDuplicate) {
  91039. selection.concat(this.entries);
  91040. }
  91041. else {
  91042. selection.concatWithNoDuplicate(this.entries);
  91043. }
  91044. }
  91045. };
  91046. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91047. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91048. if (this.blocks) {
  91049. for (var index = 0; index < this.blocks.length; index++) {
  91050. var block = this.blocks[index];
  91051. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91052. }
  91053. return;
  91054. }
  91055. if (allowDuplicate) {
  91056. selection.concat(this.entries);
  91057. }
  91058. else {
  91059. selection.concatWithNoDuplicate(this.entries);
  91060. }
  91061. }
  91062. };
  91063. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91064. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91065. if (this.blocks) {
  91066. for (var index = 0; index < this.blocks.length; index++) {
  91067. var block = this.blocks[index];
  91068. block.intersectsRay(ray, selection);
  91069. }
  91070. return;
  91071. }
  91072. selection.concatWithNoDuplicate(this.entries);
  91073. }
  91074. };
  91075. OctreeBlock.prototype.createInnerBlocks = function () {
  91076. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91077. };
  91078. return OctreeBlock;
  91079. }());
  91080. BABYLON.OctreeBlock = OctreeBlock;
  91081. })(BABYLON || (BABYLON = {}));
  91082. //# sourceMappingURL=babylon.octreeBlock.js.map
  91083. var BABYLON;
  91084. (function (BABYLON) {
  91085. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91086. __extends(VRDistortionCorrectionPostProcess, _super);
  91087. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91088. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91089. 'LensCenter',
  91090. 'Scale',
  91091. 'ScaleIn',
  91092. 'HmdWarpParam'
  91093. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91094. _this._isRightEye = isRightEye;
  91095. _this._distortionFactors = vrMetrics.distortionK;
  91096. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91097. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91098. _this.adaptScaleToCurrentViewport = true;
  91099. _this.onSizeChangedObservable.add(function () {
  91100. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91101. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91102. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91103. });
  91104. _this.onApplyObservable.add(function (effect) {
  91105. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91106. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91107. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91108. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91109. });
  91110. return _this;
  91111. }
  91112. return VRDistortionCorrectionPostProcess;
  91113. }(BABYLON.PostProcess));
  91114. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91115. })(BABYLON || (BABYLON = {}));
  91116. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91117. var BABYLON;
  91118. (function (BABYLON) {
  91119. /**
  91120. * Postprocess used to generate anaglyphic rendering
  91121. */
  91122. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91123. __extends(AnaglyphPostProcess, _super);
  91124. /**
  91125. * Creates a new AnaglyphPostProcess
  91126. * @param name defines postprocess name
  91127. * @param options defines creation options or target ratio scale
  91128. * @param rigCameras defines cameras using this postprocess
  91129. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91130. * @param engine defines hosting engine
  91131. * @param reusable defines if the postprocess will be reused multiple times per frame
  91132. */
  91133. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91134. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91135. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91136. _this.onApplyObservable.add(function (effect) {
  91137. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91138. });
  91139. return _this;
  91140. }
  91141. return AnaglyphPostProcess;
  91142. }(BABYLON.PostProcess));
  91143. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91144. })(BABYLON || (BABYLON = {}));
  91145. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91146. var BABYLON;
  91147. (function (BABYLON) {
  91148. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  91149. __extends(StereoscopicInterlacePostProcess, _super);
  91150. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  91151. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  91152. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91153. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91154. _this.onSizeChangedObservable.add(function () {
  91155. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91156. });
  91157. _this.onApplyObservable.add(function (effect) {
  91158. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  91159. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  91160. });
  91161. return _this;
  91162. }
  91163. return StereoscopicInterlacePostProcess;
  91164. }(BABYLON.PostProcess));
  91165. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  91166. })(BABYLON || (BABYLON = {}));
  91167. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  91168. var BABYLON;
  91169. (function (BABYLON) {
  91170. /**
  91171. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91172. * Screen rotation is taken into account.
  91173. */
  91174. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91175. function FreeCameraDeviceOrientationInput() {
  91176. var _this = this;
  91177. this._screenOrientationAngle = 0;
  91178. this._screenQuaternion = new BABYLON.Quaternion();
  91179. this._alpha = 0;
  91180. this._beta = 0;
  91181. this._gamma = 0;
  91182. this._orientationChanged = function () {
  91183. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91184. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91185. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91186. };
  91187. this._deviceOrientation = function (evt) {
  91188. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91189. _this._beta = evt.beta !== null ? evt.beta : 0;
  91190. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91191. };
  91192. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91193. this._orientationChanged();
  91194. }
  91195. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91196. get: function () {
  91197. return this._camera;
  91198. },
  91199. set: function (camera) {
  91200. this._camera = camera;
  91201. if (this._camera != null && !this._camera.rotationQuaternion) {
  91202. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91203. }
  91204. },
  91205. enumerable: true,
  91206. configurable: true
  91207. });
  91208. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91209. window.addEventListener("orientationchange", this._orientationChanged);
  91210. window.addEventListener("deviceorientation", this._deviceOrientation);
  91211. //In certain cases, the attach control is called AFTER orientation was changed,
  91212. //So this is needed.
  91213. this._orientationChanged();
  91214. };
  91215. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91216. window.removeEventListener("orientationchange", this._orientationChanged);
  91217. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91218. };
  91219. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91220. //if no device orientation provided, don't update the rotation.
  91221. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91222. if (!this._alpha)
  91223. return;
  91224. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91225. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91226. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91227. //Mirror on XY Plane
  91228. this._camera.rotationQuaternion.z *= -1;
  91229. this._camera.rotationQuaternion.w *= -1;
  91230. };
  91231. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91232. return "FreeCameraDeviceOrientationInput";
  91233. };
  91234. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91235. return "deviceOrientation";
  91236. };
  91237. return FreeCameraDeviceOrientationInput;
  91238. }());
  91239. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91240. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91241. })(BABYLON || (BABYLON = {}));
  91242. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91243. var BABYLON;
  91244. (function (BABYLON) {
  91245. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91246. function ArcRotateCameraVRDeviceOrientationInput() {
  91247. this.alphaCorrection = 1;
  91248. this.betaCorrection = 1;
  91249. this.gammaCorrection = 1;
  91250. this._alpha = 0;
  91251. this._gamma = 0;
  91252. this._dirty = false;
  91253. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91254. }
  91255. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91256. this.camera.attachControl(element, noPreventDefault);
  91257. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91258. };
  91259. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91260. if (evt.alpha !== null) {
  91261. this._alpha = +evt.alpha | 0;
  91262. }
  91263. if (evt.gamma !== null) {
  91264. this._gamma = +evt.gamma | 0;
  91265. }
  91266. this._dirty = true;
  91267. };
  91268. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91269. if (this._dirty) {
  91270. this._dirty = false;
  91271. if (this._gamma < 0) {
  91272. this._gamma = 180 + this._gamma;
  91273. }
  91274. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91275. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91276. }
  91277. };
  91278. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91279. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91280. };
  91281. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91282. return "ArcRotateCameraVRDeviceOrientationInput";
  91283. };
  91284. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91285. return "VRDeviceOrientation";
  91286. };
  91287. return ArcRotateCameraVRDeviceOrientationInput;
  91288. }());
  91289. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91290. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91291. })(BABYLON || (BABYLON = {}));
  91292. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91293. var BABYLON;
  91294. (function (BABYLON) {
  91295. var VRCameraMetrics = /** @class */ (function () {
  91296. function VRCameraMetrics() {
  91297. this.compensateDistortion = true;
  91298. }
  91299. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91300. get: function () {
  91301. return this.hResolution / (2 * this.vResolution);
  91302. },
  91303. enumerable: true,
  91304. configurable: true
  91305. });
  91306. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91307. get: function () {
  91308. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91309. },
  91310. enumerable: true,
  91311. configurable: true
  91312. });
  91313. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91314. get: function () {
  91315. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91316. var h = (4 * meters) / this.hScreenSize;
  91317. return BABYLON.Matrix.Translation(h, 0, 0);
  91318. },
  91319. enumerable: true,
  91320. configurable: true
  91321. });
  91322. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91323. get: function () {
  91324. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91325. var h = (4 * meters) / this.hScreenSize;
  91326. return BABYLON.Matrix.Translation(-h, 0, 0);
  91327. },
  91328. enumerable: true,
  91329. configurable: true
  91330. });
  91331. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91332. get: function () {
  91333. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91334. },
  91335. enumerable: true,
  91336. configurable: true
  91337. });
  91338. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91339. get: function () {
  91340. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91341. },
  91342. enumerable: true,
  91343. configurable: true
  91344. });
  91345. VRCameraMetrics.GetDefault = function () {
  91346. var result = new VRCameraMetrics();
  91347. result.hResolution = 1280;
  91348. result.vResolution = 800;
  91349. result.hScreenSize = 0.149759993;
  91350. result.vScreenSize = 0.0935999975;
  91351. result.vScreenCenter = 0.0467999987;
  91352. result.eyeToScreenDistance = 0.0410000011;
  91353. result.lensSeparationDistance = 0.0635000020;
  91354. result.interpupillaryDistance = 0.0640000030;
  91355. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91356. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91357. result.postProcessScaleFactor = 1.714605507808412;
  91358. result.lensCenterOffset = 0.151976421;
  91359. return result;
  91360. };
  91361. return VRCameraMetrics;
  91362. }());
  91363. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91364. })(BABYLON || (BABYLON = {}));
  91365. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91366. var BABYLON;
  91367. (function (BABYLON) {
  91368. /**
  91369. * This represents a WebVR camera.
  91370. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91371. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91372. */
  91373. var WebVRFreeCamera = /** @class */ (function (_super) {
  91374. __extends(WebVRFreeCamera, _super);
  91375. /**
  91376. * Instantiates a WebVRFreeCamera.
  91377. * @param name The name of the WebVRFreeCamera
  91378. * @param position The starting anchor position for the camera
  91379. * @param scene The scene the camera belongs to
  91380. * @param webVROptions a set of customizable options for the webVRCamera
  91381. */
  91382. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91383. if (webVROptions === void 0) { webVROptions = {}; }
  91384. var _this = _super.call(this, name, position, scene) || this;
  91385. _this.webVROptions = webVROptions;
  91386. /**
  91387. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91388. */
  91389. _this._vrDevice = null;
  91390. /**
  91391. * The rawPose of the vrDevice.
  91392. */
  91393. _this.rawPose = null;
  91394. _this._specsVersion = "1.1";
  91395. _this._attached = false;
  91396. _this._descendants = [];
  91397. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91398. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91399. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91400. _this._standingMatrix = null;
  91401. /**
  91402. * Represents device position in babylon space.
  91403. */
  91404. _this.devicePosition = BABYLON.Vector3.Zero();
  91405. /**
  91406. * Represents device rotation in babylon space.
  91407. */
  91408. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91409. /**
  91410. * The scale of the device to be used when translating from device space to babylon space.
  91411. */
  91412. _this.deviceScaleFactor = 1;
  91413. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91414. _this._worldToDevice = BABYLON.Matrix.Identity();
  91415. /**
  91416. * References to the webVR controllers for the vrDevice.
  91417. */
  91418. _this.controllers = [];
  91419. /**
  91420. * Emits an event when a controller is attached.
  91421. */
  91422. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91423. /**
  91424. * Emits an event when a controller's mesh has been loaded;
  91425. */
  91426. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91427. /**
  91428. * If the rig cameras be used as parent instead of this camera.
  91429. */
  91430. _this.rigParenting = true;
  91431. _this._defaultHeight = undefined;
  91432. _this._workingVector = BABYLON.Vector3.Zero();
  91433. _this._oneVector = BABYLON.Vector3.One();
  91434. _this._workingMatrix = BABYLON.Matrix.Identity();
  91435. _this._cache.position = BABYLON.Vector3.Zero();
  91436. if (webVROptions.defaultHeight) {
  91437. _this._defaultHeight = webVROptions.defaultHeight;
  91438. _this.position.y = _this._defaultHeight;
  91439. }
  91440. _this.minZ = 0.1;
  91441. //legacy support - the compensation boolean was removed.
  91442. if (arguments.length === 5) {
  91443. _this.webVROptions = arguments[4];
  91444. }
  91445. // default webVR options
  91446. if (_this.webVROptions.trackPosition == undefined) {
  91447. _this.webVROptions.trackPosition = true;
  91448. }
  91449. if (_this.webVROptions.controllerMeshes == undefined) {
  91450. _this.webVROptions.controllerMeshes = true;
  91451. }
  91452. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91453. _this.webVROptions.defaultLightingOnControllers = true;
  91454. }
  91455. _this.rotationQuaternion = new BABYLON.Quaternion();
  91456. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91457. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91458. }
  91459. //enable VR
  91460. var engine = _this.getEngine();
  91461. _this._onVREnabled = function (success) { if (success) {
  91462. _this.initControllers();
  91463. } };
  91464. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91465. engine.initWebVR().add(function (event) {
  91466. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91467. return;
  91468. }
  91469. _this._vrDevice = event.vrDisplay;
  91470. //reset the rig parameters.
  91471. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91472. if (_this._attached) {
  91473. _this.getEngine().enableVR();
  91474. }
  91475. });
  91476. if (typeof (VRFrameData) !== "undefined")
  91477. _this._frameData = new VRFrameData();
  91478. /**
  91479. * The idea behind the following lines:
  91480. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91481. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91482. * the second will not show it correctly.
  91483. *
  91484. * To solve this - each object that has the camera as parent will be added to a protected array.
  91485. * When the rig camera renders, it will take this array and set all of those to be its children.
  91486. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91487. * Amazing!
  91488. */
  91489. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91490. if (camera.parent === _this && _this.rigParenting) {
  91491. _this._descendants = _this.getDescendants(true, function (n) {
  91492. // don't take the cameras or the controllers!
  91493. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91494. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91495. return !isController && !isRigCamera;
  91496. });
  91497. _this._descendants.forEach(function (node) {
  91498. node.parent = camera;
  91499. });
  91500. }
  91501. });
  91502. scene.onAfterCameraRenderObservable.add(function (camera) {
  91503. if (camera.parent === _this && _this.rigParenting) {
  91504. _this._descendants.forEach(function (node) {
  91505. node.parent = _this;
  91506. });
  91507. }
  91508. });
  91509. return _this;
  91510. }
  91511. /**
  91512. * Gets the device distance from the ground in meters.
  91513. * @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.
  91514. */
  91515. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91516. if (this._standingMatrix) {
  91517. // Add standing matrix offset to get real offset from ground in room
  91518. this._standingMatrix.getTranslationToRef(this._workingVector);
  91519. return this._deviceRoomPosition.y + this._workingVector.y;
  91520. }
  91521. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91522. return this._defaultHeight || 0;
  91523. };
  91524. /**
  91525. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91526. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91527. */
  91528. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91529. var _this = this;
  91530. if (callback === void 0) { callback = function (bool) { }; }
  91531. // Use standing matrix if available
  91532. this.getEngine().initWebVRAsync().then(function (result) {
  91533. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91534. callback(false);
  91535. }
  91536. else {
  91537. _this._standingMatrix = new BABYLON.Matrix();
  91538. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91539. if (!_this.getScene().useRightHandedSystem) {
  91540. [2, 6, 8, 9, 14].forEach(function (num) {
  91541. if (_this._standingMatrix) {
  91542. _this._standingMatrix.m[num] *= -1;
  91543. }
  91544. });
  91545. }
  91546. callback(true);
  91547. }
  91548. });
  91549. };
  91550. /**
  91551. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91552. * @returns A promise with a boolean set to if the standing matrix is supported.
  91553. */
  91554. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91555. var _this = this;
  91556. return new Promise(function (res, rej) {
  91557. _this.useStandingMatrix(function (supported) {
  91558. res(supported);
  91559. });
  91560. });
  91561. };
  91562. /**
  91563. * Disposes the camera
  91564. */
  91565. WebVRFreeCamera.prototype.dispose = function () {
  91566. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91567. _super.prototype.dispose.call(this);
  91568. };
  91569. /**
  91570. * Gets a vrController by name.
  91571. * @param name The name of the controller to retreive
  91572. * @returns the controller matching the name specified or null if not found
  91573. */
  91574. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91575. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91576. var gp = _a[_i];
  91577. if (gp.hand === name) {
  91578. return gp;
  91579. }
  91580. }
  91581. return null;
  91582. };
  91583. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91584. /**
  91585. * The controller corrisponding to the users left hand.
  91586. */
  91587. get: function () {
  91588. if (!this._leftController) {
  91589. this._leftController = this.getControllerByName("left");
  91590. }
  91591. return this._leftController;
  91592. },
  91593. enumerable: true,
  91594. configurable: true
  91595. });
  91596. ;
  91597. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91598. /**
  91599. * The controller corrisponding to the users right hand.
  91600. */
  91601. get: function () {
  91602. if (!this._rightController) {
  91603. this._rightController = this.getControllerByName("right");
  91604. }
  91605. return this._rightController;
  91606. },
  91607. enumerable: true,
  91608. configurable: true
  91609. });
  91610. ;
  91611. /**
  91612. * Casts a ray forward from the vrCamera's gaze.
  91613. * @param length Length of the ray (default: 100)
  91614. * @returns the ray corrisponding to the gaze
  91615. */
  91616. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91617. if (length === void 0) { length = 100; }
  91618. if (this.leftCamera) {
  91619. // Use left eye to avoid computation to compute center on every call
  91620. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91621. }
  91622. else {
  91623. return _super.prototype.getForwardRay.call(this, length);
  91624. }
  91625. };
  91626. /**
  91627. * Updates the camera based on device's frame data
  91628. */
  91629. WebVRFreeCamera.prototype._checkInputs = function () {
  91630. if (this._vrDevice && this._vrDevice.isPresenting) {
  91631. this._vrDevice.getFrameData(this._frameData);
  91632. this.updateFromDevice(this._frameData.pose);
  91633. }
  91634. _super.prototype._checkInputs.call(this);
  91635. };
  91636. /**
  91637. * Updates the poseControlled values based on the input device pose.
  91638. * @param poseData Pose coming from the device
  91639. */
  91640. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91641. if (poseData && poseData.orientation) {
  91642. this.rawPose = poseData;
  91643. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91644. if (this.getScene().useRightHandedSystem) {
  91645. this._deviceRoomRotationQuaternion.z *= -1;
  91646. this._deviceRoomRotationQuaternion.w *= -1;
  91647. }
  91648. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91649. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91650. if (this.getScene().useRightHandedSystem) {
  91651. this._deviceRoomPosition.z *= -1;
  91652. }
  91653. }
  91654. }
  91655. };
  91656. /**
  91657. * WebVR's attach control will start broadcasting frames to the device.
  91658. * Note that in certain browsers (chrome for example) this function must be called
  91659. * within a user-interaction callback. Example:
  91660. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91661. *
  91662. * @param element html element to attach the vrDevice to
  91663. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91664. */
  91665. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91666. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91667. this._attached = true;
  91668. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91669. if (this._vrDevice) {
  91670. this.getEngine().enableVR();
  91671. }
  91672. };
  91673. /**
  91674. * Detaches the camera from the html element and disables VR
  91675. *
  91676. * @param element html element to detach from
  91677. */
  91678. WebVRFreeCamera.prototype.detachControl = function (element) {
  91679. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91680. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91681. _super.prototype.detachControl.call(this, element);
  91682. this._attached = false;
  91683. this.getEngine().disableVR();
  91684. };
  91685. /**
  91686. * @returns the name of this class
  91687. */
  91688. WebVRFreeCamera.prototype.getClassName = function () {
  91689. return "WebVRFreeCamera";
  91690. };
  91691. /**
  91692. * Calls resetPose on the vrDisplay
  91693. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91694. */
  91695. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91696. //uses the vrDisplay's "resetPose()".
  91697. //pitch and roll won't be affected.
  91698. this._vrDevice.resetPose();
  91699. };
  91700. /**
  91701. * Updates the rig cameras (left and right eye)
  91702. */
  91703. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91704. var camLeft = this._rigCameras[0];
  91705. var camRight = this._rigCameras[1];
  91706. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91707. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91708. camLeft.position.copyFrom(this._deviceRoomPosition);
  91709. camRight.position.copyFrom(this._deviceRoomPosition);
  91710. };
  91711. /**
  91712. * Updates the cached values of the camera
  91713. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91714. */
  91715. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91716. var _this = this;
  91717. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91718. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91719. if (!this.updateCacheCalled) {
  91720. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91721. this.updateCacheCalled = true;
  91722. this.update();
  91723. }
  91724. // Set working vector to the device position in room space rotated by the new rotation
  91725. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91726. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91727. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91728. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91729. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91730. // Add translation from anchor position
  91731. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91732. this._workingVector.addInPlace(this.position);
  91733. this._workingVector.subtractInPlace(this._cache.position);
  91734. this._deviceToWorld.setTranslation(this._workingVector);
  91735. // Set an inverted matrix to be used when updating the camera
  91736. this._deviceToWorld.invertToRef(this._worldToDevice);
  91737. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91738. this.controllers.forEach(function (controller) {
  91739. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91740. controller.update();
  91741. });
  91742. }
  91743. if (!ignoreParentClass) {
  91744. _super.prototype._updateCache.call(this);
  91745. }
  91746. this.updateCacheCalled = false;
  91747. };
  91748. /**
  91749. * Updates the current device position and rotation in the babylon world
  91750. */
  91751. WebVRFreeCamera.prototype.update = function () {
  91752. // Get current device position in babylon world
  91753. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91754. // Get current device rotation in babylon world
  91755. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91756. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91757. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91758. _super.prototype.update.call(this);
  91759. };
  91760. /**
  91761. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91762. * @returns an identity matrix
  91763. */
  91764. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91765. return BABYLON.Matrix.Identity();
  91766. };
  91767. /**
  91768. * This function is called by the two RIG cameras.
  91769. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91770. */
  91771. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91772. var _this = this;
  91773. // Update the parent camera prior to using a child camera to avoid desynchronization
  91774. var parentCamera = this._cameraRigParams["parentCamera"];
  91775. parentCamera._updateCache();
  91776. //WebVR 1.1
  91777. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91778. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91779. if (!this.getScene().useRightHandedSystem) {
  91780. [2, 6, 8, 9, 14].forEach(function (num) {
  91781. _this._webvrViewMatrix.m[num] *= -1;
  91782. });
  91783. }
  91784. // update the camera rotation matrix
  91785. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91786. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91787. // Computing target and final matrix
  91788. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91789. // should the view matrix be updated with scale and position offset?
  91790. if (parentCamera.deviceScaleFactor !== 1) {
  91791. this._webvrViewMatrix.invert();
  91792. // scale the position, if set
  91793. if (parentCamera.deviceScaleFactor) {
  91794. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91795. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91796. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91797. }
  91798. this._webvrViewMatrix.invert();
  91799. }
  91800. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91801. // Compute global position
  91802. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91803. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91804. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91805. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91806. this._markSyncedWithParent();
  91807. return this._webvrViewMatrix;
  91808. };
  91809. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91810. var _this = this;
  91811. var parentCamera = this.parent;
  91812. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91813. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91814. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91815. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91816. //babylon compatible matrix
  91817. if (!this.getScene().useRightHandedSystem) {
  91818. [8, 9, 10, 11].forEach(function (num) {
  91819. _this._projectionMatrix.m[num] *= -1;
  91820. });
  91821. }
  91822. return this._projectionMatrix;
  91823. };
  91824. /**
  91825. * Initializes the controllers and their meshes
  91826. */
  91827. WebVRFreeCamera.prototype.initControllers = function () {
  91828. var _this = this;
  91829. this.controllers = [];
  91830. var manager = this.getScene().gamepadManager;
  91831. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91832. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91833. var webVrController = gamepad;
  91834. if (webVrController.defaultModel) {
  91835. webVrController.defaultModel.setEnabled(false);
  91836. }
  91837. if (webVrController.hand === "right") {
  91838. _this._rightController = null;
  91839. }
  91840. if (webVrController.hand === "left") {
  91841. _this._leftController = null;
  91842. }
  91843. var controllerIndex = _this.controllers.indexOf(webVrController);
  91844. if (controllerIndex !== -1) {
  91845. _this.controllers.splice(controllerIndex, 1);
  91846. }
  91847. }
  91848. });
  91849. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91850. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91851. var webVrController_1 = gamepad;
  91852. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91853. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91854. if (_this.webVROptions.controllerMeshes) {
  91855. if (webVrController_1.defaultModel) {
  91856. webVrController_1.defaultModel.setEnabled(true);
  91857. }
  91858. else {
  91859. // Load the meshes
  91860. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91861. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91862. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91863. if (_this.webVROptions.defaultLightingOnControllers) {
  91864. if (!_this._lightOnControllers) {
  91865. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91866. }
  91867. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91868. var children = mesh.getChildren();
  91869. if (children.length !== 0) {
  91870. children.forEach(function (mesh) {
  91871. light.includedOnlyMeshes.push(mesh);
  91872. activateLightOnSubMeshes_1(mesh, light);
  91873. });
  91874. }
  91875. };
  91876. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91877. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91878. }
  91879. });
  91880. }
  91881. }
  91882. webVrController_1.attachToPoseControlledCamera(_this);
  91883. // since this is async - sanity check. Is the controller already stored?
  91884. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91885. //add to the controllers array
  91886. _this.controllers.push(webVrController_1);
  91887. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91888. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91889. // So we're overriding setting left & right manually to be sure
  91890. var firstViveWandDetected = false;
  91891. for (var i = 0; i < _this.controllers.length; i++) {
  91892. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91893. if (!firstViveWandDetected) {
  91894. firstViveWandDetected = true;
  91895. _this.controllers[i].hand = "left";
  91896. }
  91897. else {
  91898. _this.controllers[i].hand = "right";
  91899. }
  91900. }
  91901. }
  91902. //did we find enough controllers? Great! let the developer know.
  91903. if (_this.controllers.length >= 2) {
  91904. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91905. }
  91906. }
  91907. }
  91908. });
  91909. };
  91910. return WebVRFreeCamera;
  91911. }(BABYLON.FreeCamera));
  91912. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91913. })(BABYLON || (BABYLON = {}));
  91914. //# sourceMappingURL=babylon.webVRCamera.js.map
  91915. var BABYLON;
  91916. (function (BABYLON) {
  91917. // We're mainly based on the logic defined into the FreeCamera code
  91918. /**
  91919. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91920. * being tilted forward or back and left or right.
  91921. */
  91922. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91923. __extends(DeviceOrientationCamera, _super);
  91924. /**
  91925. * Creates a new device orientation camera
  91926. * @param name The name of the camera
  91927. * @param position The start position camera
  91928. * @param scene The scene the camera belongs to
  91929. */
  91930. function DeviceOrientationCamera(name, position, scene) {
  91931. var _this = _super.call(this, name, position, scene) || this;
  91932. _this._quaternionCache = new BABYLON.Quaternion();
  91933. _this.inputs.addDeviceOrientation();
  91934. return _this;
  91935. }
  91936. /**
  91937. * Gets the current instance class name ("DeviceOrientationCamera").
  91938. * This helps avoiding instanceof at run time.
  91939. * @returns the class name
  91940. */
  91941. DeviceOrientationCamera.prototype.getClassName = function () {
  91942. return "DeviceOrientationCamera";
  91943. };
  91944. /**
  91945. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91946. */
  91947. DeviceOrientationCamera.prototype._checkInputs = function () {
  91948. _super.prototype._checkInputs.call(this);
  91949. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91950. if (this._initialQuaternion) {
  91951. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91952. }
  91953. };
  91954. /**
  91955. * Reset the camera to its default orientation on the specified axis only.
  91956. * @param axis The axis to reset
  91957. */
  91958. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91959. var _this = this;
  91960. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91961. //can only work if this camera has a rotation quaternion already.
  91962. if (!this.rotationQuaternion)
  91963. return;
  91964. if (!this._initialQuaternion) {
  91965. this._initialQuaternion = new BABYLON.Quaternion();
  91966. }
  91967. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91968. ['x', 'y', 'z'].forEach(function (axisName) {
  91969. if (!axis[axisName]) {
  91970. _this._initialQuaternion[axisName] = 0;
  91971. }
  91972. else {
  91973. _this._initialQuaternion[axisName] *= -1;
  91974. }
  91975. });
  91976. this._initialQuaternion.normalize();
  91977. //force rotation update
  91978. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91979. };
  91980. return DeviceOrientationCamera;
  91981. }(BABYLON.FreeCamera));
  91982. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  91983. })(BABYLON || (BABYLON = {}));
  91984. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  91985. var BABYLON;
  91986. (function (BABYLON) {
  91987. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  91988. __extends(VRDeviceOrientationFreeCamera, _super);
  91989. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91990. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91991. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91992. var _this = _super.call(this, name, position, scene) || this;
  91993. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91994. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91995. return _this;
  91996. }
  91997. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  91998. return "VRDeviceOrientationFreeCamera";
  91999. };
  92000. return VRDeviceOrientationFreeCamera;
  92001. }(BABYLON.DeviceOrientationCamera));
  92002. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92003. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92004. __extends(VRDeviceOrientationGamepadCamera, _super);
  92005. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92006. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92007. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92008. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92009. _this.inputs.addGamepad();
  92010. return _this;
  92011. }
  92012. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92013. return "VRDeviceOrientationGamepadCamera";
  92014. };
  92015. return VRDeviceOrientationGamepadCamera;
  92016. }(VRDeviceOrientationFreeCamera));
  92017. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92018. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92019. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92020. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92021. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92022. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92023. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92024. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92025. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92026. _this.inputs.addVRDeviceOrientation();
  92027. return _this;
  92028. }
  92029. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92030. return "VRDeviceOrientationArcRotateCamera";
  92031. };
  92032. return VRDeviceOrientationArcRotateCamera;
  92033. }(BABYLON.ArcRotateCamera));
  92034. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92035. })(BABYLON || (BABYLON = {}));
  92036. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  92037. var BABYLON;
  92038. (function (BABYLON) {
  92039. /**
  92040. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  92041. */
  92042. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  92043. __extends(AnaglyphFreeCamera, _super);
  92044. /**
  92045. * Creates a new AnaglyphFreeCamera
  92046. * @param name defines camera name
  92047. * @param position defines initial position
  92048. * @param interaxialDistance defines distance between each color axis
  92049. * @param scene defines the hosting scene
  92050. */
  92051. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  92052. var _this = _super.call(this, name, position, scene) || this;
  92053. _this.interaxialDistance = interaxialDistance;
  92054. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92055. return _this;
  92056. }
  92057. /**
  92058. * Gets camera class name
  92059. * @returns AnaglyphFreeCamera
  92060. */
  92061. AnaglyphFreeCamera.prototype.getClassName = function () {
  92062. return "AnaglyphFreeCamera";
  92063. };
  92064. return AnaglyphFreeCamera;
  92065. }(BABYLON.FreeCamera));
  92066. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92067. /**
  92068. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  92069. */
  92070. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  92071. __extends(AnaglyphArcRotateCamera, _super);
  92072. /**
  92073. * Creates a new AnaglyphArcRotateCamera
  92074. * @param name defines camera name
  92075. * @param alpha defines alpha angle (in radians)
  92076. * @param beta defines beta angle (in radians)
  92077. * @param radius defines radius
  92078. * @param target defines camera target
  92079. * @param interaxialDistance defines distance between each color axis
  92080. * @param scene defines the hosting scene
  92081. */
  92082. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  92083. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92084. _this.interaxialDistance = interaxialDistance;
  92085. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92086. return _this;
  92087. }
  92088. /**
  92089. * Gets camera class name
  92090. * @returns AnaglyphArcRotateCamera
  92091. */
  92092. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  92093. return "AnaglyphArcRotateCamera";
  92094. };
  92095. return AnaglyphArcRotateCamera;
  92096. }(BABYLON.ArcRotateCamera));
  92097. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  92098. /**
  92099. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92100. */
  92101. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92102. __extends(AnaglyphGamepadCamera, _super);
  92103. /**
  92104. * Creates a new AnaglyphGamepadCamera
  92105. * @param name defines camera name
  92106. * @param position defines initial position
  92107. * @param interaxialDistance defines distance between each color axis
  92108. * @param scene defines the hosting scene
  92109. */
  92110. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92111. var _this = _super.call(this, name, position, scene) || this;
  92112. _this.interaxialDistance = interaxialDistance;
  92113. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92114. return _this;
  92115. }
  92116. /**
  92117. * Gets camera class name
  92118. * @returns AnaglyphGamepadCamera
  92119. */
  92120. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92121. return "AnaglyphGamepadCamera";
  92122. };
  92123. return AnaglyphGamepadCamera;
  92124. }(BABYLON.GamepadCamera));
  92125. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92126. /**
  92127. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92128. */
  92129. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92130. __extends(AnaglyphUniversalCamera, _super);
  92131. /**
  92132. * Creates a new AnaglyphUniversalCamera
  92133. * @param name defines camera name
  92134. * @param position defines initial position
  92135. * @param interaxialDistance defines distance between each color axis
  92136. * @param scene defines the hosting scene
  92137. */
  92138. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92139. var _this = _super.call(this, name, position, scene) || this;
  92140. _this.interaxialDistance = interaxialDistance;
  92141. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92142. return _this;
  92143. }
  92144. /**
  92145. * Gets camera class name
  92146. * @returns AnaglyphUniversalCamera
  92147. */
  92148. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92149. return "AnaglyphUniversalCamera";
  92150. };
  92151. return AnaglyphUniversalCamera;
  92152. }(BABYLON.UniversalCamera));
  92153. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92154. /**
  92155. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92156. */
  92157. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92158. __extends(StereoscopicFreeCamera, _super);
  92159. /**
  92160. * Creates a new StereoscopicFreeCamera
  92161. * @param name defines camera name
  92162. * @param position defines initial position
  92163. * @param interaxialDistance defines distance between each color axis
  92164. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92165. * @param scene defines the hosting scene
  92166. */
  92167. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92168. var _this = _super.call(this, name, position, scene) || this;
  92169. _this.interaxialDistance = interaxialDistance;
  92170. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92171. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92172. return _this;
  92173. }
  92174. /**
  92175. * Gets camera class name
  92176. * @returns StereoscopicFreeCamera
  92177. */
  92178. StereoscopicFreeCamera.prototype.getClassName = function () {
  92179. return "StereoscopicFreeCamera";
  92180. };
  92181. return StereoscopicFreeCamera;
  92182. }(BABYLON.FreeCamera));
  92183. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92184. /**
  92185. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92186. */
  92187. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92188. __extends(StereoscopicArcRotateCamera, _super);
  92189. /**
  92190. * Creates a new StereoscopicArcRotateCamera
  92191. * @param name defines camera name
  92192. * @param alpha defines alpha angle (in radians)
  92193. * @param beta defines beta angle (in radians)
  92194. * @param radius defines radius
  92195. * @param target defines camera target
  92196. * @param interaxialDistance defines distance between each color axis
  92197. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92198. * @param scene defines the hosting scene
  92199. */
  92200. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92201. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92202. _this.interaxialDistance = interaxialDistance;
  92203. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92204. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92205. return _this;
  92206. }
  92207. /**
  92208. * Gets camera class name
  92209. * @returns StereoscopicArcRotateCamera
  92210. */
  92211. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92212. return "StereoscopicArcRotateCamera";
  92213. };
  92214. return StereoscopicArcRotateCamera;
  92215. }(BABYLON.ArcRotateCamera));
  92216. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92217. /**
  92218. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92219. */
  92220. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92221. __extends(StereoscopicGamepadCamera, _super);
  92222. /**
  92223. * Creates a new StereoscopicGamepadCamera
  92224. * @param name defines camera name
  92225. * @param position defines initial position
  92226. * @param interaxialDistance defines distance between each color axis
  92227. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92228. * @param scene defines the hosting scene
  92229. */
  92230. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92231. var _this = _super.call(this, name, position, scene) || this;
  92232. _this.interaxialDistance = interaxialDistance;
  92233. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92234. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92235. return _this;
  92236. }
  92237. /**
  92238. * Gets camera class name
  92239. * @returns StereoscopicGamepadCamera
  92240. */
  92241. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92242. return "StereoscopicGamepadCamera";
  92243. };
  92244. return StereoscopicGamepadCamera;
  92245. }(BABYLON.GamepadCamera));
  92246. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92247. /**
  92248. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92249. */
  92250. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92251. __extends(StereoscopicUniversalCamera, _super);
  92252. /**
  92253. * Creates a new StereoscopicUniversalCamera
  92254. * @param name defines camera name
  92255. * @param position defines initial position
  92256. * @param interaxialDistance defines distance between each color axis
  92257. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92258. * @param scene defines the hosting scene
  92259. */
  92260. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92261. var _this = _super.call(this, name, position, scene) || this;
  92262. _this.interaxialDistance = interaxialDistance;
  92263. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92264. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92265. return _this;
  92266. }
  92267. /**
  92268. * Gets camera class name
  92269. * @returns StereoscopicUniversalCamera
  92270. */
  92271. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92272. return "StereoscopicUniversalCamera";
  92273. };
  92274. return StereoscopicUniversalCamera;
  92275. }(BABYLON.UniversalCamera));
  92276. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92277. })(BABYLON || (BABYLON = {}));
  92278. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  92279. var BABYLON;
  92280. (function (BABYLON) {
  92281. var VRExperienceHelperGazer = /** @class */ (function () {
  92282. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92283. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92284. this.scene = scene;
  92285. this._pointerDownOnMeshAsked = false;
  92286. this._isActionableMesh = false;
  92287. this._teleportationRequestInitiated = false;
  92288. this._teleportationBackRequestInitiated = false;
  92289. this._rotationRightAsked = false;
  92290. this._rotationLeftAsked = false;
  92291. this._dpadPressed = true;
  92292. this._activePointer = false;
  92293. this._id = VRExperienceHelperGazer._idCounter++;
  92294. // Gaze tracker
  92295. if (!gazeTrackerToClone) {
  92296. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92297. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92298. this._gazeTracker.isPickable = false;
  92299. this._gazeTracker.isVisible = false;
  92300. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92301. targetMat.specularColor = BABYLON.Color3.Black();
  92302. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92303. targetMat.backFaceCulling = false;
  92304. this._gazeTracker.material = targetMat;
  92305. }
  92306. else {
  92307. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92308. }
  92309. }
  92310. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92311. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92312. };
  92313. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92314. this._pointerDownOnMeshAsked = true;
  92315. if (this._currentHit) {
  92316. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92317. }
  92318. };
  92319. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92320. if (this._currentHit) {
  92321. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92322. }
  92323. this._pointerDownOnMeshAsked = false;
  92324. };
  92325. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92326. this._activePointer = true;
  92327. };
  92328. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92329. this._activePointer = false;
  92330. };
  92331. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92332. if (distance === void 0) { distance = 100; }
  92333. };
  92334. VRExperienceHelperGazer.prototype.dispose = function () {
  92335. this._interactionsEnabled = false;
  92336. this._teleportationEnabled = false;
  92337. if (this._gazeTracker) {
  92338. this._gazeTracker.dispose();
  92339. }
  92340. };
  92341. VRExperienceHelperGazer._idCounter = 0;
  92342. return VRExperienceHelperGazer;
  92343. }());
  92344. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92345. __extends(VRExperienceHelperControllerGazer, _super);
  92346. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92347. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92348. _this.webVRController = webVRController;
  92349. // Laser pointer
  92350. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92351. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92352. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92353. laserPointerMaterial.alpha = 0.6;
  92354. _this._laserPointer.material = laserPointerMaterial;
  92355. _this._laserPointer.rotation.x = Math.PI / 2;
  92356. _this._laserPointer.position.z = -0.5;
  92357. _this._laserPointer.isVisible = false;
  92358. _this._laserPointer.isPickable = false;
  92359. if (!webVRController.mesh) {
  92360. // Create an empty mesh that is used prior to loading the high quality model
  92361. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92362. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92363. preloadPointerPose.rotation.x = -0.7;
  92364. preloadMesh.addChild(preloadPointerPose);
  92365. webVRController.attachToMesh(preloadMesh);
  92366. }
  92367. _this._setLaserPointerParent(webVRController.mesh);
  92368. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92369. _this._setLaserPointerParent(mesh);
  92370. });
  92371. return _this;
  92372. }
  92373. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92374. return this.webVRController.getForwardRay(length);
  92375. };
  92376. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92377. _super.prototype._activatePointer.call(this);
  92378. this._laserPointer.isVisible = true;
  92379. };
  92380. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92381. _super.prototype._deactivatePointer.call(this);
  92382. this._laserPointer.isVisible = false;
  92383. };
  92384. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92385. this._laserPointer.material.emissiveColor = color;
  92386. };
  92387. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92388. var makeNotPick = function (root) {
  92389. root.name += " laserPointer";
  92390. root.isPickable = false;
  92391. root.getChildMeshes().forEach(function (c) {
  92392. makeNotPick(c);
  92393. });
  92394. };
  92395. makeNotPick(mesh);
  92396. var childMeshes = mesh.getChildMeshes();
  92397. this.webVRController._pointingPoseNode = null;
  92398. for (var i = 0; i < childMeshes.length; i++) {
  92399. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92400. mesh = childMeshes[i];
  92401. this.webVRController._pointingPoseNode = mesh;
  92402. break;
  92403. }
  92404. }
  92405. this._laserPointer.parent = mesh;
  92406. };
  92407. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92408. if (distance === void 0) { distance = 100; }
  92409. this._laserPointer.scaling.y = distance;
  92410. this._laserPointer.position.z = -distance / 2;
  92411. };
  92412. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92413. _super.prototype.dispose.call(this);
  92414. this._laserPointer.dispose();
  92415. if (this._meshAttachedObserver) {
  92416. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92417. }
  92418. };
  92419. return VRExperienceHelperControllerGazer;
  92420. }(VRExperienceHelperGazer));
  92421. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92422. __extends(VRExperienceHelperCameraGazer, _super);
  92423. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92424. var _this = _super.call(this, scene) || this;
  92425. _this.getCamera = getCamera;
  92426. return _this;
  92427. }
  92428. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92429. var camera = this.getCamera();
  92430. if (camera) {
  92431. return camera.getForwardRay(length);
  92432. }
  92433. else {
  92434. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92435. }
  92436. };
  92437. return VRExperienceHelperCameraGazer;
  92438. }(VRExperienceHelperGazer));
  92439. /**
  92440. * Helps to quickly add VR support to an existing scene.
  92441. * See http://doc.babylonjs.com/how_to/webvr_helper
  92442. */
  92443. var VRExperienceHelper = /** @class */ (function () {
  92444. /**
  92445. * Instantiates a VRExperienceHelper.
  92446. * Helps to quickly add VR support to an existing scene.
  92447. * @param scene The scene the VRExperienceHelper belongs to.
  92448. * @param webVROptions Options to modify the vr experience helper's behavior.
  92449. */
  92450. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92451. if (webVROptions === void 0) { webVROptions = {}; }
  92452. var _this = this;
  92453. this.webVROptions = webVROptions;
  92454. // Can the system support WebVR, even if a headset isn't plugged in?
  92455. this._webVRsupported = false;
  92456. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92457. this._webVRready = false;
  92458. // Are we waiting for the requestPresent callback to complete?
  92459. this._webVRrequesting = false;
  92460. // Are we presenting to the headset right now?
  92461. this._webVRpresenting = false;
  92462. // Are we presenting in the fullscreen fallback?
  92463. this._fullscreenVRpresenting = false;
  92464. /**
  92465. * Observable raised when entering VR.
  92466. */
  92467. this.onEnteringVRObservable = new BABYLON.Observable();
  92468. /**
  92469. * Observable raised when exiting VR.
  92470. */
  92471. this.onExitingVRObservable = new BABYLON.Observable();
  92472. /**
  92473. * Observable raised when controller mesh is loaded.
  92474. */
  92475. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92476. this._useCustomVRButton = false;
  92477. this._teleportationRequested = false;
  92478. this._teleportActive = false;
  92479. this._floorMeshesCollection = [];
  92480. this._rotationAllowed = true;
  92481. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92482. this._isDefaultTeleportationTarget = true;
  92483. this._teleportationFillColor = "#444444";
  92484. this._teleportationBorderColor = "#FFFFFF";
  92485. this._rotationAngle = 0;
  92486. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92487. this._padSensibilityUp = 0.65;
  92488. this._padSensibilityDown = 0.35;
  92489. this.leftController = null;
  92490. this.rightController = null;
  92491. /**
  92492. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92493. */
  92494. this.onNewMeshSelected = new BABYLON.Observable();
  92495. /**
  92496. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92497. */
  92498. this.onNewMeshPicked = new BABYLON.Observable();
  92499. /**
  92500. * Observable raised before camera teleportation
  92501. */
  92502. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92503. /**
  92504. * Observable raised after camera teleportation
  92505. */
  92506. this.onAfterCameraTeleport = new BABYLON.Observable();
  92507. /**
  92508. * Observable raised when current selected mesh gets unselected
  92509. */
  92510. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92511. /**
  92512. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92513. */
  92514. this.teleportationEnabled = true;
  92515. this._teleportationInitialized = false;
  92516. this._interactionsEnabled = false;
  92517. this._interactionsRequested = false;
  92518. this._displayGaze = true;
  92519. this._displayLaserPointer = true;
  92520. this._onResize = function () {
  92521. _this.moveButtonToBottomRight();
  92522. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92523. _this.exitVR();
  92524. }
  92525. };
  92526. this._onFullscreenChange = function () {
  92527. if (document.fullscreen !== undefined) {
  92528. _this._fullscreenVRpresenting = document.fullscreen;
  92529. }
  92530. else if (document.mozFullScreen !== undefined) {
  92531. _this._fullscreenVRpresenting = document.mozFullScreen;
  92532. }
  92533. else if (document.webkitIsFullScreen !== undefined) {
  92534. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92535. }
  92536. else if (document.msIsFullScreen !== undefined) {
  92537. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92538. }
  92539. else if (document.msFullscreenElement !== undefined) {
  92540. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92541. }
  92542. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92543. _this.exitVR();
  92544. if (!_this._useCustomVRButton) {
  92545. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92546. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92547. }
  92548. }
  92549. };
  92550. this.beforeRender = function () {
  92551. if (_this.leftController && _this.leftController._activePointer) {
  92552. _this._castRayAndSelectObject(_this.leftController);
  92553. }
  92554. if (_this.rightController && _this.rightController._activePointer) {
  92555. _this._castRayAndSelectObject(_this.rightController);
  92556. }
  92557. if (_this._noControllerIsActive) {
  92558. _this._castRayAndSelectObject(_this._cameraGazer);
  92559. }
  92560. else {
  92561. _this._cameraGazer._gazeTracker.isVisible = false;
  92562. }
  92563. };
  92564. this._onNewGamepadConnected = function (gamepad) {
  92565. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92566. if (gamepad.leftStick) {
  92567. gamepad.onleftstickchanged(function (stickValues) {
  92568. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92569. // Listening to classic/xbox gamepad only if no VR controller is active
  92570. if ((!_this.leftController && !_this.rightController) ||
  92571. ((_this.leftController && !_this.leftController._activePointer) &&
  92572. (_this.rightController && !_this.rightController._activePointer))) {
  92573. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92574. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92575. }
  92576. }
  92577. });
  92578. }
  92579. if (gamepad.rightStick) {
  92580. gamepad.onrightstickchanged(function (stickValues) {
  92581. if (_this._teleportationInitialized) {
  92582. _this._checkRotate(stickValues, _this._cameraGazer);
  92583. }
  92584. });
  92585. }
  92586. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92587. gamepad.onbuttondown(function (buttonPressed) {
  92588. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92589. _this._cameraGazer._selectionPointerDown();
  92590. }
  92591. });
  92592. gamepad.onbuttonup(function (buttonPressed) {
  92593. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92594. _this._cameraGazer._selectionPointerUp();
  92595. }
  92596. });
  92597. }
  92598. }
  92599. else {
  92600. var webVRController = gamepad;
  92601. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92602. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92603. _this.rightController = controller;
  92604. }
  92605. else {
  92606. _this.leftController = controller;
  92607. }
  92608. _this._tryEnableInteractionOnController(controller);
  92609. }
  92610. };
  92611. // 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
  92612. this._tryEnableInteractionOnController = function (controller) {
  92613. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92614. _this._enableInteractionOnController(controller);
  92615. }
  92616. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92617. _this._enableTeleportationOnController(controller);
  92618. }
  92619. };
  92620. this._onNewGamepadDisconnected = function (gamepad) {
  92621. if (gamepad instanceof BABYLON.WebVRController) {
  92622. if (gamepad.hand === "left" && _this.leftController != null) {
  92623. _this.leftController.dispose();
  92624. _this.leftController = null;
  92625. }
  92626. if (gamepad.hand === "right" && _this.rightController != null) {
  92627. _this.rightController.dispose();
  92628. _this.rightController = null;
  92629. }
  92630. }
  92631. };
  92632. this._workingVector = BABYLON.Vector3.Zero();
  92633. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92634. this._workingMatrix = BABYLON.Matrix.Identity();
  92635. this._scene = scene;
  92636. this._canvas = scene.getEngine().getRenderingCanvas();
  92637. // Parse options
  92638. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92639. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92640. }
  92641. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92642. webVROptions.createDeviceOrientationCamera = true;
  92643. }
  92644. if (webVROptions.laserToggle === undefined) {
  92645. webVROptions.laserToggle = true;
  92646. }
  92647. if (webVROptions.defaultHeight === undefined) {
  92648. webVROptions.defaultHeight = 1.7;
  92649. }
  92650. if (webVROptions.useCustomVRButton) {
  92651. this._useCustomVRButton = true;
  92652. if (webVROptions.customVRButton) {
  92653. this._btnVR = webVROptions.customVRButton;
  92654. }
  92655. }
  92656. if (webVROptions.rayLength) {
  92657. this._rayLength = webVROptions.rayLength;
  92658. }
  92659. this._defaultHeight = webVROptions.defaultHeight;
  92660. if (webVROptions.positionScale) {
  92661. this._rayLength *= webVROptions.positionScale;
  92662. this._defaultHeight *= webVROptions.positionScale;
  92663. }
  92664. // Set position
  92665. if (this._scene.activeCamera) {
  92666. this._position = this._scene.activeCamera.position.clone();
  92667. }
  92668. else {
  92669. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92670. }
  92671. // Set non-vr camera
  92672. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92673. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92674. // Copy data from existing camera
  92675. if (this._scene.activeCamera) {
  92676. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92677. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92678. // Set rotation from previous camera
  92679. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92680. var targetCamera = this._scene.activeCamera;
  92681. if (targetCamera.rotationQuaternion) {
  92682. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92683. }
  92684. else {
  92685. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92686. }
  92687. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92688. }
  92689. }
  92690. this._scene.activeCamera = this._deviceOrientationCamera;
  92691. if (this._canvas) {
  92692. this._scene.activeCamera.attachControl(this._canvas);
  92693. }
  92694. }
  92695. else {
  92696. this._existingCamera = this._scene.activeCamera;
  92697. }
  92698. // Create VR cameras
  92699. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92700. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92701. }
  92702. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92703. this._webVRCamera.useStandingMatrix();
  92704. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92705. // Create default button
  92706. if (!this._useCustomVRButton) {
  92707. this._btnVR = document.createElement("BUTTON");
  92708. this._btnVR.className = "babylonVRicon";
  92709. this._btnVR.id = "babylonVRiconbtn";
  92710. this._btnVR.title = "Click to switch to VR";
  92711. 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) }";
  92712. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92713. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92714. // css += ".babylonVRicon.vrdisplaysupported { }";
  92715. // css += ".babylonVRicon.vrdisplayready { }";
  92716. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92717. var style = document.createElement('style');
  92718. style.appendChild(document.createTextNode(css));
  92719. document.getElementsByTagName('head')[0].appendChild(style);
  92720. this.moveButtonToBottomRight();
  92721. }
  92722. // VR button click event
  92723. if (this._btnVR) {
  92724. this._btnVR.addEventListener("click", function () {
  92725. if (!_this.isInVRMode) {
  92726. _this.enterVR();
  92727. }
  92728. else {
  92729. _this.exitVR();
  92730. }
  92731. });
  92732. }
  92733. // Window events
  92734. window.addEventListener("resize", this._onResize);
  92735. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92736. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92737. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92738. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92739. document.onmsfullscreenchange = this._onFullscreenChange;
  92740. // Display vr button when headset is connected
  92741. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92742. this.displayVRButton();
  92743. }
  92744. else {
  92745. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92746. if (e.vrDisplay) {
  92747. _this.displayVRButton();
  92748. }
  92749. });
  92750. }
  92751. // Exiting VR mode using 'ESC' key on desktop
  92752. this._onKeyDown = function (event) {
  92753. if (event.keyCode === 27 && _this.isInVRMode) {
  92754. _this.exitVR();
  92755. }
  92756. };
  92757. document.addEventListener("keydown", this._onKeyDown);
  92758. // Exiting VR mode double tapping the touch screen
  92759. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92760. if (_this.isInVRMode) {
  92761. _this.exitVR();
  92762. if (_this._fullscreenVRpresenting) {
  92763. _this._scene.getEngine().switchFullscreen(true);
  92764. }
  92765. }
  92766. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92767. // Listen for WebVR display changes
  92768. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92769. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92770. this._onVRRequestPresentStart = function () {
  92771. _this._webVRrequesting = true;
  92772. _this.updateButtonVisibility();
  92773. };
  92774. this._onVRRequestPresentComplete = function (success) {
  92775. _this._webVRrequesting = false;
  92776. _this.updateButtonVisibility();
  92777. };
  92778. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92779. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92780. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92781. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92782. scene.onDisposeObservable.add(function () {
  92783. _this.dispose();
  92784. });
  92785. // Gamepad connection events
  92786. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92787. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92788. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92789. this.updateButtonVisibility();
  92790. //create easing functions
  92791. this._circleEase = new BABYLON.CircleEase();
  92792. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92793. if (this.webVROptions.floorMeshes) {
  92794. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92795. }
  92796. }
  92797. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92798. /** Return this.onEnteringVRObservable
  92799. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92800. */
  92801. get: function () {
  92802. return this.onEnteringVRObservable;
  92803. },
  92804. enumerable: true,
  92805. configurable: true
  92806. });
  92807. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92808. /** Return this.onExitingVRObservable
  92809. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92810. */
  92811. get: function () {
  92812. return this.onExitingVRObservable;
  92813. },
  92814. enumerable: true,
  92815. configurable: true
  92816. });
  92817. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92818. /** Return this.onControllerMeshLoadedObservable
  92819. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92820. */
  92821. get: function () {
  92822. return this.onControllerMeshLoadedObservable;
  92823. },
  92824. enumerable: true,
  92825. configurable: true
  92826. });
  92827. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92828. /**
  92829. * The mesh used to display where the user is going to teleport.
  92830. */
  92831. get: function () {
  92832. return this._teleportationTarget;
  92833. },
  92834. /**
  92835. * Sets the mesh to be used to display where the user is going to teleport.
  92836. */
  92837. set: function (value) {
  92838. if (value) {
  92839. value.name = "teleportationTarget";
  92840. this._isDefaultTeleportationTarget = false;
  92841. this._teleportationTarget = value;
  92842. }
  92843. },
  92844. enumerable: true,
  92845. configurable: true
  92846. });
  92847. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92848. /**
  92849. * The mesh used to display where the user is selecting,
  92850. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92851. * See http://doc.babylonjs.com/resources/baking_transformations
  92852. */
  92853. get: function () {
  92854. return this._cameraGazer._gazeTracker;
  92855. },
  92856. set: function (value) {
  92857. if (value) {
  92858. this._cameraGazer._gazeTracker = value;
  92859. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92860. this._cameraGazer._gazeTracker.isPickable = false;
  92861. this._cameraGazer._gazeTracker.isVisible = false;
  92862. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92863. if (this.leftController) {
  92864. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92865. }
  92866. if (this.rightController) {
  92867. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92868. }
  92869. }
  92870. },
  92871. enumerable: true,
  92872. configurable: true
  92873. });
  92874. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92875. /**
  92876. * If the ray of the gaze should be displayed.
  92877. */
  92878. get: function () {
  92879. return this._displayGaze;
  92880. },
  92881. /**
  92882. * Sets if the ray of the gaze should be displayed.
  92883. */
  92884. set: function (value) {
  92885. this._displayGaze = value;
  92886. if (!value) {
  92887. this._cameraGazer._gazeTracker.isVisible = false;
  92888. if (this.leftController) {
  92889. this.leftController._gazeTracker.isVisible = false;
  92890. }
  92891. if (this.rightController) {
  92892. this.rightController._gazeTracker.isVisible = false;
  92893. }
  92894. }
  92895. },
  92896. enumerable: true,
  92897. configurable: true
  92898. });
  92899. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92900. /**
  92901. * If the ray of the LaserPointer should be displayed.
  92902. */
  92903. get: function () {
  92904. return this._displayLaserPointer;
  92905. },
  92906. /**
  92907. * Sets if the ray of the LaserPointer should be displayed.
  92908. */
  92909. set: function (value) {
  92910. this._displayLaserPointer = value;
  92911. if (!value) {
  92912. if (this.rightController) {
  92913. this.rightController._deactivatePointer();
  92914. this.rightController._gazeTracker.isVisible = false;
  92915. }
  92916. if (this.leftController) {
  92917. this.leftController._deactivatePointer();
  92918. this.leftController._gazeTracker.isVisible = false;
  92919. }
  92920. }
  92921. else {
  92922. if (this.rightController) {
  92923. this.rightController._activatePointer();
  92924. }
  92925. if (this.leftController) {
  92926. this.leftController._activatePointer();
  92927. }
  92928. }
  92929. },
  92930. enumerable: true,
  92931. configurable: true
  92932. });
  92933. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92934. /**
  92935. * The deviceOrientationCamera used as the camera when not in VR.
  92936. */
  92937. get: function () {
  92938. return this._deviceOrientationCamera;
  92939. },
  92940. enumerable: true,
  92941. configurable: true
  92942. });
  92943. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92944. /**
  92945. * Based on the current WebVR support, returns the current VR camera used.
  92946. */
  92947. get: function () {
  92948. if (this._webVRready) {
  92949. return this._webVRCamera;
  92950. }
  92951. else {
  92952. return this._scene.activeCamera;
  92953. }
  92954. },
  92955. enumerable: true,
  92956. configurable: true
  92957. });
  92958. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92959. /**
  92960. * The webVRCamera which is used when in VR.
  92961. */
  92962. get: function () {
  92963. return this._webVRCamera;
  92964. },
  92965. enumerable: true,
  92966. configurable: true
  92967. });
  92968. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92969. /**
  92970. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92971. */
  92972. get: function () {
  92973. return this._vrDeviceOrientationCamera;
  92974. },
  92975. enumerable: true,
  92976. configurable: true
  92977. });
  92978. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92979. get: function () {
  92980. var result = this._cameraGazer._teleportationRequestInitiated
  92981. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92982. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92983. return result;
  92984. },
  92985. enumerable: true,
  92986. configurable: true
  92987. });
  92988. // Raised when one of the controller has loaded successfully its associated default mesh
  92989. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92990. if (this.leftController && this.leftController.webVRController == webVRController) {
  92991. if (webVRController.mesh) {
  92992. this.leftController._setLaserPointerParent(webVRController.mesh);
  92993. }
  92994. }
  92995. if (this.rightController && this.rightController.webVRController == webVRController) {
  92996. if (webVRController.mesh) {
  92997. this.rightController._setLaserPointerParent(webVRController.mesh);
  92998. }
  92999. }
  93000. try {
  93001. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93002. }
  93003. catch (err) {
  93004. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93005. }
  93006. };
  93007. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93008. /**
  93009. * Gets a value indicating if we are currently in VR mode.
  93010. */
  93011. get: function () {
  93012. return this._webVRpresenting || this._fullscreenVRpresenting;
  93013. },
  93014. enumerable: true,
  93015. configurable: true
  93016. });
  93017. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93018. var vrDisplay = this._scene.getEngine().getVRDevice();
  93019. if (vrDisplay) {
  93020. var wasPresenting = this._webVRpresenting;
  93021. // A VR display is connected
  93022. this._webVRpresenting = vrDisplay.isPresenting;
  93023. if (wasPresenting && !this._webVRpresenting)
  93024. this.exitVR();
  93025. }
  93026. else {
  93027. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93028. }
  93029. this.updateButtonVisibility();
  93030. };
  93031. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93032. this._webVRsupported = eventArgs.vrSupported;
  93033. this._webVRready = !!eventArgs.vrDisplay;
  93034. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93035. this.updateButtonVisibility();
  93036. };
  93037. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93038. if (this._canvas && !this._useCustomVRButton) {
  93039. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93040. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93041. }
  93042. };
  93043. VRExperienceHelper.prototype.displayVRButton = function () {
  93044. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93045. document.body.appendChild(this._btnVR);
  93046. this._btnVRDisplayed = true;
  93047. }
  93048. };
  93049. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93050. if (!this._btnVR || this._useCustomVRButton) {
  93051. return;
  93052. }
  93053. this._btnVR.className = "babylonVRicon";
  93054. if (this.isInVRMode) {
  93055. this._btnVR.className += " vrdisplaypresenting";
  93056. }
  93057. else {
  93058. if (this._webVRready)
  93059. this._btnVR.className += " vrdisplayready";
  93060. if (this._webVRsupported)
  93061. this._btnVR.className += " vrdisplaysupported";
  93062. if (this._webVRrequesting)
  93063. this._btnVR.className += " vrdisplayrequesting";
  93064. }
  93065. };
  93066. /**
  93067. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93068. * Otherwise, will use the fullscreen API.
  93069. */
  93070. VRExperienceHelper.prototype.enterVR = function () {
  93071. if (this.onEnteringVRObservable) {
  93072. try {
  93073. this.onEnteringVRObservable.notifyObservers(this);
  93074. }
  93075. catch (err) {
  93076. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93077. }
  93078. }
  93079. if (this._scene.activeCamera) {
  93080. this._position = this._scene.activeCamera.position.clone();
  93081. // make sure that we return to the last active camera
  93082. this._existingCamera = this._scene.activeCamera;
  93083. }
  93084. if (this._webVRrequesting)
  93085. return;
  93086. // If WebVR is supported and a headset is connected
  93087. if (this._webVRready) {
  93088. if (!this._webVRpresenting) {
  93089. this._webVRCamera.position = this._position;
  93090. this._scene.activeCamera = this._webVRCamera;
  93091. }
  93092. }
  93093. else if (this._vrDeviceOrientationCamera) {
  93094. this._vrDeviceOrientationCamera.position = this._position;
  93095. if (this._scene.activeCamera) {
  93096. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93097. }
  93098. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93099. this._scene.getEngine().switchFullscreen(true);
  93100. this.updateButtonVisibility();
  93101. }
  93102. if (this._scene.activeCamera && this._canvas) {
  93103. this._scene.activeCamera.attachControl(this._canvas);
  93104. }
  93105. if (this._interactionsEnabled) {
  93106. this._scene.registerBeforeRender(this.beforeRender);
  93107. }
  93108. };
  93109. /**
  93110. * Attempt to exit VR, or fullscreen.
  93111. */
  93112. VRExperienceHelper.prototype.exitVR = function () {
  93113. if (this.onExitingVRObservable) {
  93114. try {
  93115. this.onExitingVRObservable.notifyObservers(this);
  93116. }
  93117. catch (err) {
  93118. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93119. }
  93120. }
  93121. if (this._webVRpresenting) {
  93122. this._scene.getEngine().disableVR();
  93123. }
  93124. if (this._scene.activeCamera) {
  93125. this._position = this._scene.activeCamera.position.clone();
  93126. }
  93127. if (this._deviceOrientationCamera) {
  93128. this._deviceOrientationCamera.position = this._position;
  93129. this._scene.activeCamera = this._deviceOrientationCamera;
  93130. if (this._canvas) {
  93131. this._scene.activeCamera.attachControl(this._canvas);
  93132. }
  93133. }
  93134. else if (this._existingCamera) {
  93135. this._existingCamera.position = this._position;
  93136. this._scene.activeCamera = this._existingCamera;
  93137. }
  93138. this.updateButtonVisibility();
  93139. if (this._interactionsEnabled) {
  93140. this._scene.unregisterBeforeRender(this.beforeRender);
  93141. }
  93142. // resize to update width and height when exiting vr exits fullscreen
  93143. this._scene.getEngine().resize();
  93144. };
  93145. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93146. /**
  93147. * The position of the vr experience helper.
  93148. */
  93149. get: function () {
  93150. return this._position;
  93151. },
  93152. /**
  93153. * Sets the position of the vr experience helper.
  93154. */
  93155. set: function (value) {
  93156. this._position = value;
  93157. if (this._scene.activeCamera) {
  93158. this._scene.activeCamera.position = value;
  93159. }
  93160. },
  93161. enumerable: true,
  93162. configurable: true
  93163. });
  93164. /**
  93165. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  93166. */
  93167. VRExperienceHelper.prototype.enableInteractions = function () {
  93168. var _this = this;
  93169. if (!this._interactionsEnabled) {
  93170. this._interactionsRequested = true;
  93171. if (this.leftController) {
  93172. this._enableInteractionOnController(this.leftController);
  93173. }
  93174. if (this.rightController) {
  93175. this._enableInteractionOnController(this.rightController);
  93176. }
  93177. this.raySelectionPredicate = function (mesh) {
  93178. return mesh.isVisible;
  93179. };
  93180. this.meshSelectionPredicate = function (mesh) {
  93181. return true;
  93182. };
  93183. this._raySelectionPredicate = function (mesh) {
  93184. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93185. && mesh.name.indexOf("teleportationTarget") === -1
  93186. && mesh.name.indexOf("torusTeleportation") === -1
  93187. && mesh.name.indexOf("laserPointer") === -1)) {
  93188. return _this.raySelectionPredicate(mesh);
  93189. }
  93190. return false;
  93191. };
  93192. this._interactionsEnabled = true;
  93193. }
  93194. };
  93195. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93196. get: function () {
  93197. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93198. },
  93199. enumerable: true,
  93200. configurable: true
  93201. });
  93202. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93203. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93204. if (this._floorMeshesCollection[i].id === mesh.id) {
  93205. return true;
  93206. }
  93207. }
  93208. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93209. return true;
  93210. }
  93211. return false;
  93212. };
  93213. /**
  93214. * Adds a floor mesh to be used for teleportation.
  93215. * @param floorMesh the mesh to be used for teleportation.
  93216. */
  93217. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93218. if (!this._floorMeshesCollection) {
  93219. return;
  93220. }
  93221. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93222. return;
  93223. }
  93224. this._floorMeshesCollection.push(floorMesh);
  93225. };
  93226. /**
  93227. * Removes a floor mesh from being used for teleportation.
  93228. * @param floorMesh the mesh to be removed.
  93229. */
  93230. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93231. if (!this._floorMeshesCollection) {
  93232. return;
  93233. }
  93234. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93235. if (meshIndex !== -1) {
  93236. this._floorMeshesCollection.splice(meshIndex, 1);
  93237. }
  93238. };
  93239. /**
  93240. * Enables interactions and teleportation using the VR controllers and gaze.
  93241. * @param vrTeleportationOptions options to modify teleportation behavior.
  93242. */
  93243. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93244. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93245. if (!this._teleportationInitialized) {
  93246. this._teleportationRequested = true;
  93247. this.enableInteractions();
  93248. if (vrTeleportationOptions.floorMeshName) {
  93249. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93250. }
  93251. if (vrTeleportationOptions.floorMeshes) {
  93252. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93253. }
  93254. if (this.leftController != null) {
  93255. this._enableTeleportationOnController(this.leftController);
  93256. }
  93257. if (this.rightController != null) {
  93258. this._enableTeleportationOnController(this.rightController);
  93259. }
  93260. // Creates an image processing post process for the vignette not relying
  93261. // on the main scene configuration for image processing to reduce setup and spaces
  93262. // (gamma/linear) conflicts.
  93263. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93264. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93265. imageProcessingConfiguration.vignetteEnabled = true;
  93266. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93267. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93268. this._teleportationInitialized = true;
  93269. if (this._isDefaultTeleportationTarget) {
  93270. this._createTeleportationCircles();
  93271. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93272. }
  93273. }
  93274. };
  93275. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93276. var _this = this;
  93277. var controllerMesh = controller.webVRController.mesh;
  93278. if (controllerMesh) {
  93279. controller._interactionsEnabled = true;
  93280. controller._activatePointer();
  93281. if (this.webVROptions.laserToggle) {
  93282. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93283. // Enabling / disabling laserPointer
  93284. if (_this._displayLaserPointer && stateObject.value === 1) {
  93285. if (controller._activePointer) {
  93286. controller._deactivatePointer();
  93287. }
  93288. else {
  93289. controller._activatePointer();
  93290. }
  93291. if (_this.displayGaze) {
  93292. controller._gazeTracker.isVisible = controller._activePointer;
  93293. }
  93294. }
  93295. });
  93296. }
  93297. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93298. var gazer = controller;
  93299. if (_this._noControllerIsActive) {
  93300. gazer = _this._cameraGazer;
  93301. }
  93302. if (!gazer._pointerDownOnMeshAsked) {
  93303. if (stateObject.value > _this._padSensibilityUp) {
  93304. gazer._selectionPointerDown();
  93305. }
  93306. }
  93307. else if (stateObject.value < _this._padSensibilityDown) {
  93308. gazer._selectionPointerUp();
  93309. }
  93310. });
  93311. }
  93312. };
  93313. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93314. // Dont teleport if another gaze already requested teleportation
  93315. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93316. return;
  93317. }
  93318. if (!gazer._teleportationRequestInitiated) {
  93319. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93320. gazer._activatePointer();
  93321. gazer._teleportationRequestInitiated = true;
  93322. }
  93323. }
  93324. else {
  93325. // Listening to the proper controller values changes to confirm teleportation
  93326. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93327. if (this._teleportActive) {
  93328. this._teleportCamera(this._haloCenter);
  93329. }
  93330. gazer._teleportationRequestInitiated = false;
  93331. }
  93332. }
  93333. };
  93334. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93335. // Only rotate when user is not currently selecting a teleportation location
  93336. if (gazer._teleportationRequestInitiated) {
  93337. return;
  93338. }
  93339. if (!gazer._rotationLeftAsked) {
  93340. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93341. gazer._rotationLeftAsked = true;
  93342. if (this._rotationAllowed) {
  93343. this._rotateCamera(false);
  93344. }
  93345. }
  93346. }
  93347. else {
  93348. if (stateObject.x > -this._padSensibilityDown) {
  93349. gazer._rotationLeftAsked = false;
  93350. }
  93351. }
  93352. if (!gazer._rotationRightAsked) {
  93353. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93354. gazer._rotationRightAsked = true;
  93355. if (this._rotationAllowed) {
  93356. this._rotateCamera(true);
  93357. }
  93358. }
  93359. }
  93360. else {
  93361. if (stateObject.x < this._padSensibilityDown) {
  93362. gazer._rotationRightAsked = false;
  93363. }
  93364. }
  93365. };
  93366. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93367. // Only teleport backwards when user is not currently selecting a teleportation location
  93368. if (gazer._teleportationRequestInitiated) {
  93369. return;
  93370. }
  93371. // Teleport backwards
  93372. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93373. if (!gazer._teleportationBackRequestInitiated) {
  93374. if (!this.currentVRCamera) {
  93375. return;
  93376. }
  93377. // Get rotation and position of the current camera
  93378. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93379. var position = this.currentVRCamera.position;
  93380. // If the camera has device position, use that instead
  93381. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93382. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93383. position = this.currentVRCamera.devicePosition;
  93384. }
  93385. // Get matrix with only the y rotation of the device rotation
  93386. rotation.toEulerAnglesToRef(this._workingVector);
  93387. this._workingVector.z = 0;
  93388. this._workingVector.x = 0;
  93389. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93390. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93391. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93392. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93393. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93394. var ray = new BABYLON.Ray(position, this._workingVector);
  93395. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93396. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93397. this._teleportCamera(hit.pickedPoint);
  93398. }
  93399. gazer._teleportationBackRequestInitiated = true;
  93400. }
  93401. }
  93402. else {
  93403. gazer._teleportationBackRequestInitiated = false;
  93404. }
  93405. };
  93406. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93407. var _this = this;
  93408. var controllerMesh = controller.webVRController.mesh;
  93409. if (controllerMesh) {
  93410. if (!controller._interactionsEnabled) {
  93411. this._enableInteractionOnController(controller);
  93412. }
  93413. controller._interactionsEnabled = true;
  93414. controller._teleportationEnabled = true;
  93415. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93416. controller._dpadPressed = false;
  93417. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93418. controller._dpadPressed = stateObject.pressed;
  93419. if (!controller._dpadPressed) {
  93420. controller._rotationLeftAsked = false;
  93421. controller._rotationRightAsked = false;
  93422. controller._teleportationBackRequestInitiated = false;
  93423. }
  93424. });
  93425. }
  93426. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93427. if (_this.teleportationEnabled) {
  93428. _this._checkTeleportBackwards(stateObject, controller);
  93429. _this._checkTeleportWithRay(stateObject, controller);
  93430. }
  93431. _this._checkRotate(stateObject, controller);
  93432. });
  93433. }
  93434. };
  93435. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93436. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93437. this._teleportationTarget.isPickable = false;
  93438. var length = 512;
  93439. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93440. dynamicTexture.hasAlpha = true;
  93441. var context = dynamicTexture.getContext();
  93442. var centerX = length / 2;
  93443. var centerY = length / 2;
  93444. var radius = 200;
  93445. context.beginPath();
  93446. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93447. context.fillStyle = this._teleportationFillColor;
  93448. context.fill();
  93449. context.lineWidth = 10;
  93450. context.strokeStyle = this._teleportationBorderColor;
  93451. context.stroke();
  93452. context.closePath();
  93453. dynamicTexture.update();
  93454. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93455. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93456. this._teleportationTarget.material = teleportationCircleMaterial;
  93457. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93458. torus.isPickable = false;
  93459. torus.parent = this._teleportationTarget;
  93460. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93461. var keys = [];
  93462. keys.push({
  93463. frame: 0,
  93464. value: 0
  93465. });
  93466. keys.push({
  93467. frame: 30,
  93468. value: 0.4
  93469. });
  93470. keys.push({
  93471. frame: 60,
  93472. value: 0
  93473. });
  93474. animationInnerCircle.setKeys(keys);
  93475. var easingFunction = new BABYLON.SineEase();
  93476. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93477. animationInnerCircle.setEasingFunction(easingFunction);
  93478. torus.animations = [];
  93479. torus.animations.push(animationInnerCircle);
  93480. this._scene.beginAnimation(torus, 0, 60, true);
  93481. this._hideTeleportationTarget();
  93482. };
  93483. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93484. this._teleportActive = true;
  93485. if (this._teleportationInitialized) {
  93486. this._teleportationTarget.isVisible = true;
  93487. if (this._isDefaultTeleportationTarget) {
  93488. this._teleportationTarget.getChildren()[0].isVisible = true;
  93489. }
  93490. }
  93491. };
  93492. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93493. this._teleportActive = false;
  93494. if (this._teleportationInitialized) {
  93495. this._teleportationTarget.isVisible = false;
  93496. if (this._isDefaultTeleportationTarget) {
  93497. this._teleportationTarget.getChildren()[0].isVisible = false;
  93498. }
  93499. }
  93500. };
  93501. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93502. var _this = this;
  93503. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93504. return;
  93505. }
  93506. if (right) {
  93507. this._rotationAngle++;
  93508. }
  93509. else {
  93510. this._rotationAngle--;
  93511. }
  93512. this.currentVRCamera.animations = [];
  93513. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93514. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93515. var animationRotationKeys = [];
  93516. animationRotationKeys.push({
  93517. frame: 0,
  93518. value: this.currentVRCamera.rotationQuaternion
  93519. });
  93520. animationRotationKeys.push({
  93521. frame: 6,
  93522. value: target
  93523. });
  93524. animationRotation.setKeys(animationRotationKeys);
  93525. animationRotation.setEasingFunction(this._circleEase);
  93526. this.currentVRCamera.animations.push(animationRotation);
  93527. this._postProcessMove.animations = [];
  93528. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93529. var vignetteWeightKeys = [];
  93530. vignetteWeightKeys.push({
  93531. frame: 0,
  93532. value: 0
  93533. });
  93534. vignetteWeightKeys.push({
  93535. frame: 3,
  93536. value: 4
  93537. });
  93538. vignetteWeightKeys.push({
  93539. frame: 6,
  93540. value: 0
  93541. });
  93542. animationPP.setKeys(vignetteWeightKeys);
  93543. animationPP.setEasingFunction(this._circleEase);
  93544. this._postProcessMove.animations.push(animationPP);
  93545. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93546. var vignetteStretchKeys = [];
  93547. vignetteStretchKeys.push({
  93548. frame: 0,
  93549. value: 0
  93550. });
  93551. vignetteStretchKeys.push({
  93552. frame: 3,
  93553. value: 10
  93554. });
  93555. vignetteStretchKeys.push({
  93556. frame: 6,
  93557. value: 0
  93558. });
  93559. animationPP2.setKeys(vignetteStretchKeys);
  93560. animationPP2.setEasingFunction(this._circleEase);
  93561. this._postProcessMove.animations.push(animationPP2);
  93562. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93563. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93564. this._postProcessMove.samples = 4;
  93565. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93566. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93567. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93568. });
  93569. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93570. };
  93571. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93572. if (hit.pickedPoint) {
  93573. if (gazer._teleportationRequestInitiated) {
  93574. this._displayTeleportationTarget();
  93575. this._haloCenter.copyFrom(hit.pickedPoint);
  93576. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93577. }
  93578. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93579. if (pickNormal) {
  93580. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93581. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93582. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93583. }
  93584. this._teleportationTarget.position.y += 0.1;
  93585. }
  93586. };
  93587. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93588. var _this = this;
  93589. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93590. return;
  93591. }
  93592. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93593. // offset of the headset from the anchor.
  93594. if (this.webVRCamera.leftCamera) {
  93595. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93596. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93597. location.subtractToRef(this._workingVector, this._workingVector);
  93598. }
  93599. else {
  93600. this._workingVector.copyFrom(location);
  93601. }
  93602. // Add height to account for user's height offset
  93603. if (this.isInVRMode) {
  93604. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93605. }
  93606. else {
  93607. this._workingVector.y += this._defaultHeight;
  93608. }
  93609. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93610. // Create animation from the camera's position to the new location
  93611. this.currentVRCamera.animations = [];
  93612. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93613. var animationCameraTeleportationKeys = [{
  93614. frame: 0,
  93615. value: this.currentVRCamera.position
  93616. },
  93617. {
  93618. frame: 11,
  93619. value: this._workingVector
  93620. }
  93621. ];
  93622. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93623. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93624. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93625. this._postProcessMove.animations = [];
  93626. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93627. var vignetteWeightKeys = [];
  93628. vignetteWeightKeys.push({
  93629. frame: 0,
  93630. value: 0
  93631. });
  93632. vignetteWeightKeys.push({
  93633. frame: 5,
  93634. value: 8
  93635. });
  93636. vignetteWeightKeys.push({
  93637. frame: 11,
  93638. value: 0
  93639. });
  93640. animationPP.setKeys(vignetteWeightKeys);
  93641. this._postProcessMove.animations.push(animationPP);
  93642. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93643. var vignetteStretchKeys = [];
  93644. vignetteStretchKeys.push({
  93645. frame: 0,
  93646. value: 0
  93647. });
  93648. vignetteStretchKeys.push({
  93649. frame: 5,
  93650. value: 10
  93651. });
  93652. vignetteStretchKeys.push({
  93653. frame: 11,
  93654. value: 0
  93655. });
  93656. animationPP2.setKeys(vignetteStretchKeys);
  93657. this._postProcessMove.animations.push(animationPP2);
  93658. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93659. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93660. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93661. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93662. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93663. });
  93664. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93665. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93666. });
  93667. this._hideTeleportationTarget();
  93668. };
  93669. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93670. if (normal) {
  93671. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93672. if (angle < Math.PI / 2) {
  93673. normal.scaleInPlace(-1);
  93674. }
  93675. }
  93676. return normal;
  93677. };
  93678. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93679. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93680. return;
  93681. }
  93682. var ray = gazer._getForwardRay(this._rayLength);
  93683. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93684. if (hit) {
  93685. // Populate the contrllers mesh that can be used for drag/drop
  93686. if (gazer._laserPointer) {
  93687. hit.originMesh = gazer._laserPointer.parent;
  93688. }
  93689. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93690. }
  93691. gazer._currentHit = hit;
  93692. // Moving the gazeTracker on the mesh face targetted
  93693. if (hit && hit.pickedPoint) {
  93694. if (this._displayGaze) {
  93695. var multiplier = 1;
  93696. gazer._gazeTracker.isVisible = true;
  93697. if (gazer._isActionableMesh) {
  93698. multiplier = 3;
  93699. }
  93700. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93701. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93702. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93703. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93704. // To avoid z-fighting
  93705. var deltaFighting = 0.002;
  93706. if (pickNormal) {
  93707. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93708. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93709. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93710. }
  93711. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93712. if (gazer._gazeTracker.position.x < 0) {
  93713. gazer._gazeTracker.position.x += deltaFighting;
  93714. }
  93715. else {
  93716. gazer._gazeTracker.position.x -= deltaFighting;
  93717. }
  93718. if (gazer._gazeTracker.position.y < 0) {
  93719. gazer._gazeTracker.position.y += deltaFighting;
  93720. }
  93721. else {
  93722. gazer._gazeTracker.position.y -= deltaFighting;
  93723. }
  93724. if (gazer._gazeTracker.position.z < 0) {
  93725. gazer._gazeTracker.position.z += deltaFighting;
  93726. }
  93727. else {
  93728. gazer._gazeTracker.position.z -= deltaFighting;
  93729. }
  93730. }
  93731. // Changing the size of the laser pointer based on the distance from the targetted point
  93732. gazer._updatePointerDistance(hit.distance);
  93733. }
  93734. else {
  93735. gazer._updatePointerDistance();
  93736. gazer._gazeTracker.isVisible = false;
  93737. }
  93738. if (hit && hit.pickedMesh) {
  93739. // The object selected is the floor, we're in a teleportation scenario
  93740. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93741. // Moving the teleportation area to this targetted point
  93742. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93743. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93744. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93745. }
  93746. gazer._currentMeshSelected = null;
  93747. if (gazer._teleportationRequestInitiated) {
  93748. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93749. }
  93750. return;
  93751. }
  93752. // If not, we're in a selection scenario
  93753. //this._teleportationAllowed = false;
  93754. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93755. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93756. this.onNewMeshPicked.notifyObservers(hit);
  93757. gazer._currentMeshSelected = hit.pickedMesh;
  93758. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93759. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93760. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93761. gazer._isActionableMesh = true;
  93762. }
  93763. else {
  93764. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93765. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93766. gazer._isActionableMesh = false;
  93767. }
  93768. try {
  93769. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93770. }
  93771. catch (err) {
  93772. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93773. }
  93774. }
  93775. else {
  93776. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93777. gazer._currentMeshSelected = null;
  93778. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93779. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93780. }
  93781. }
  93782. }
  93783. else {
  93784. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93785. gazer._currentMeshSelected = null;
  93786. //this._teleportationAllowed = false;
  93787. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93788. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93789. }
  93790. };
  93791. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93792. if (mesh) {
  93793. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93794. }
  93795. };
  93796. /**
  93797. * Sets the color of the laser ray from the vr controllers.
  93798. * @param color new color for the ray.
  93799. */
  93800. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93801. if (this.leftController) {
  93802. this.leftController._setLaserPointerColor(color);
  93803. }
  93804. if (this.rightController) {
  93805. this.rightController._setLaserPointerColor(color);
  93806. }
  93807. };
  93808. /**
  93809. * Sets the color of the ray from the vr headsets gaze.
  93810. * @param color new color for the ray.
  93811. */
  93812. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93813. if (!this._cameraGazer._gazeTracker.material) {
  93814. return;
  93815. }
  93816. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93817. if (this.leftController) {
  93818. this.leftController._gazeTracker.material.emissiveColor = color;
  93819. }
  93820. if (this.rightController) {
  93821. this.rightController._gazeTracker.material.emissiveColor = color;
  93822. }
  93823. };
  93824. /**
  93825. * Exits VR and disposes of the vr experience helper
  93826. */
  93827. VRExperienceHelper.prototype.dispose = function () {
  93828. if (this.isInVRMode) {
  93829. this.exitVR();
  93830. }
  93831. if (this._postProcessMove) {
  93832. this._postProcessMove.dispose();
  93833. }
  93834. if (this._webVRCamera) {
  93835. this._webVRCamera.dispose();
  93836. }
  93837. if (this._vrDeviceOrientationCamera) {
  93838. this._vrDeviceOrientationCamera.dispose();
  93839. }
  93840. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93841. document.body.removeChild(this._btnVR);
  93842. }
  93843. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93844. this._deviceOrientationCamera.dispose();
  93845. }
  93846. if (this._cameraGazer) {
  93847. this._cameraGazer.dispose();
  93848. }
  93849. if (this.leftController) {
  93850. this.leftController.dispose();
  93851. }
  93852. if (this.rightController) {
  93853. this.rightController.dispose();
  93854. }
  93855. if (this._teleportationTarget) {
  93856. this._teleportationTarget.dispose();
  93857. }
  93858. this._floorMeshesCollection = [];
  93859. document.removeEventListener("keydown", this._onKeyDown);
  93860. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93861. window.removeEventListener("resize", this._onResize);
  93862. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93863. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93864. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93865. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93866. document.onmsfullscreenchange = null;
  93867. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93868. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93869. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93870. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93871. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93872. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93873. this._scene.unregisterBeforeRender(this.beforeRender);
  93874. };
  93875. /**
  93876. * Gets the name of the VRExperienceHelper class
  93877. * @returns "VRExperienceHelper"
  93878. */
  93879. VRExperienceHelper.prototype.getClassName = function () {
  93880. return "VRExperienceHelper";
  93881. };
  93882. return VRExperienceHelper;
  93883. }());
  93884. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93885. })(BABYLON || (BABYLON = {}));
  93886. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93887. // Mainly based on these 2 articles :
  93888. // 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
  93889. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93890. var BABYLON;
  93891. (function (BABYLON) {
  93892. /**
  93893. * Defines the potential axis of a Joystick
  93894. */
  93895. var JoystickAxis;
  93896. (function (JoystickAxis) {
  93897. /** X axis */
  93898. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93899. /** Y axis */
  93900. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93901. /** Z axis */
  93902. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93903. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93904. /**
  93905. * Class used to define virtual joystick (used in touch mode)
  93906. */
  93907. var VirtualJoystick = /** @class */ (function () {
  93908. /**
  93909. * Creates a new virtual joystick
  93910. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93911. */
  93912. function VirtualJoystick(leftJoystick) {
  93913. var _this = this;
  93914. if (leftJoystick) {
  93915. this._leftJoystick = true;
  93916. }
  93917. else {
  93918. this._leftJoystick = false;
  93919. }
  93920. VirtualJoystick._globalJoystickIndex++;
  93921. // By default left & right arrow keys are moving the X
  93922. // and up & down keys are moving the Y
  93923. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93924. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93925. this.reverseLeftRight = false;
  93926. this.reverseUpDown = false;
  93927. // collections of pointers
  93928. this._touches = new BABYLON.StringDictionary();
  93929. this.deltaPosition = BABYLON.Vector3.Zero();
  93930. this._joystickSensibility = 25;
  93931. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93932. this._onResize = function (evt) {
  93933. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93934. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93935. if (VirtualJoystick.vjCanvas) {
  93936. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93937. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93938. }
  93939. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93940. };
  93941. // injecting a canvas element on top of the canvas 3D game
  93942. if (!VirtualJoystick.vjCanvas) {
  93943. window.addEventListener("resize", this._onResize, false);
  93944. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93945. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93946. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93947. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93948. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93949. VirtualJoystick.vjCanvas.style.width = "100%";
  93950. VirtualJoystick.vjCanvas.style.height = "100%";
  93951. VirtualJoystick.vjCanvas.style.position = "absolute";
  93952. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93953. VirtualJoystick.vjCanvas.style.top = "0px";
  93954. VirtualJoystick.vjCanvas.style.left = "0px";
  93955. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93956. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93957. // Support for jQuery PEP polyfill
  93958. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93959. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93960. if (!context) {
  93961. throw new Error("Unable to create canvas for virtual joystick");
  93962. }
  93963. VirtualJoystick.vjCanvasContext = context;
  93964. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93965. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93966. document.body.appendChild(VirtualJoystick.vjCanvas);
  93967. }
  93968. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93969. this.pressed = false;
  93970. // default joystick color
  93971. this._joystickColor = "cyan";
  93972. this._joystickPointerID = -1;
  93973. // current joystick position
  93974. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93975. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93976. // origin joystick position
  93977. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93978. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93979. this._onPointerDownHandlerRef = function (evt) {
  93980. _this._onPointerDown(evt);
  93981. };
  93982. this._onPointerMoveHandlerRef = function (evt) {
  93983. _this._onPointerMove(evt);
  93984. };
  93985. this._onPointerUpHandlerRef = function (evt) {
  93986. _this._onPointerUp(evt);
  93987. };
  93988. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93989. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93990. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93991. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93992. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93993. evt.preventDefault(); // Disables system menu
  93994. }, false);
  93995. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93996. }
  93997. /**
  93998. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93999. * @param newJoystickSensibility defines the new sensibility
  94000. */
  94001. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94002. this._joystickSensibility = newJoystickSensibility;
  94003. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94004. };
  94005. VirtualJoystick.prototype._onPointerDown = function (e) {
  94006. var positionOnScreenCondition;
  94007. e.preventDefault();
  94008. if (this._leftJoystick === true) {
  94009. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94010. }
  94011. else {
  94012. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94013. }
  94014. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94015. // First contact will be dedicated to the virtual joystick
  94016. this._joystickPointerID = e.pointerId;
  94017. this._joystickPointerStartPos.x = e.clientX;
  94018. this._joystickPointerStartPos.y = e.clientY;
  94019. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94020. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94021. this._deltaJoystickVector.x = 0;
  94022. this._deltaJoystickVector.y = 0;
  94023. this.pressed = true;
  94024. this._touches.add(e.pointerId.toString(), e);
  94025. }
  94026. else {
  94027. // You can only trigger the action buttons with a joystick declared
  94028. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94029. this._action();
  94030. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94031. }
  94032. }
  94033. };
  94034. VirtualJoystick.prototype._onPointerMove = function (e) {
  94035. // If the current pointer is the one associated to the joystick (first touch contact)
  94036. if (this._joystickPointerID == e.pointerId) {
  94037. this._joystickPointerPos.x = e.clientX;
  94038. this._joystickPointerPos.y = e.clientY;
  94039. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94040. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94041. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94042. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94043. switch (this._axisTargetedByLeftAndRight) {
  94044. case JoystickAxis.X:
  94045. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94046. break;
  94047. case JoystickAxis.Y:
  94048. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94049. break;
  94050. case JoystickAxis.Z:
  94051. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94052. break;
  94053. }
  94054. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94055. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94056. switch (this._axisTargetedByUpAndDown) {
  94057. case JoystickAxis.X:
  94058. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94059. break;
  94060. case JoystickAxis.Y:
  94061. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94062. break;
  94063. case JoystickAxis.Z:
  94064. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94065. break;
  94066. }
  94067. }
  94068. else {
  94069. var data = this._touches.get(e.pointerId.toString());
  94070. if (data) {
  94071. data.x = e.clientX;
  94072. data.y = e.clientY;
  94073. }
  94074. }
  94075. };
  94076. VirtualJoystick.prototype._onPointerUp = function (e) {
  94077. if (this._joystickPointerID == e.pointerId) {
  94078. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94079. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94080. this._joystickPointerID = -1;
  94081. this.pressed = false;
  94082. }
  94083. else {
  94084. var touch = this._touches.get(e.pointerId.toString());
  94085. if (touch) {
  94086. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94087. }
  94088. }
  94089. this._deltaJoystickVector.x = 0;
  94090. this._deltaJoystickVector.y = 0;
  94091. this._touches.remove(e.pointerId.toString());
  94092. };
  94093. /**
  94094. * Change the color of the virtual joystick
  94095. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94096. */
  94097. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94098. this._joystickColor = newColor;
  94099. };
  94100. /**
  94101. * Defines a callback to call when the joystick is touched
  94102. * @param action defines the callback
  94103. */
  94104. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94105. this._action = action;
  94106. };
  94107. /**
  94108. * Defines which axis you'd like to control for left & right
  94109. * @param axis defines the axis to use
  94110. */
  94111. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94112. switch (axis) {
  94113. case JoystickAxis.X:
  94114. case JoystickAxis.Y:
  94115. case JoystickAxis.Z:
  94116. this._axisTargetedByLeftAndRight = axis;
  94117. break;
  94118. default:
  94119. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94120. break;
  94121. }
  94122. };
  94123. /**
  94124. * Defines which axis you'd like to control for up & down
  94125. * @param axis defines the axis to use
  94126. */
  94127. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94128. switch (axis) {
  94129. case JoystickAxis.X:
  94130. case JoystickAxis.Y:
  94131. case JoystickAxis.Z:
  94132. this._axisTargetedByUpAndDown = axis;
  94133. break;
  94134. default:
  94135. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94136. break;
  94137. }
  94138. };
  94139. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94140. var _this = this;
  94141. if (this.pressed) {
  94142. this._touches.forEach(function (key, touch) {
  94143. if (touch.pointerId === _this._joystickPointerID) {
  94144. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94145. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94146. VirtualJoystick.vjCanvasContext.beginPath();
  94147. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94148. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94149. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94150. VirtualJoystick.vjCanvasContext.stroke();
  94151. VirtualJoystick.vjCanvasContext.closePath();
  94152. VirtualJoystick.vjCanvasContext.beginPath();
  94153. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94154. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94155. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94156. VirtualJoystick.vjCanvasContext.stroke();
  94157. VirtualJoystick.vjCanvasContext.closePath();
  94158. VirtualJoystick.vjCanvasContext.beginPath();
  94159. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94160. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94161. VirtualJoystick.vjCanvasContext.stroke();
  94162. VirtualJoystick.vjCanvasContext.closePath();
  94163. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94164. }
  94165. else {
  94166. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94167. VirtualJoystick.vjCanvasContext.beginPath();
  94168. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94169. VirtualJoystick.vjCanvasContext.beginPath();
  94170. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94171. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94172. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94173. VirtualJoystick.vjCanvasContext.stroke();
  94174. VirtualJoystick.vjCanvasContext.closePath();
  94175. touch.prevX = touch.x;
  94176. touch.prevY = touch.y;
  94177. }
  94178. ;
  94179. });
  94180. }
  94181. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94182. };
  94183. /**
  94184. * Release internal HTML canvas
  94185. */
  94186. VirtualJoystick.prototype.releaseCanvas = function () {
  94187. if (VirtualJoystick.vjCanvas) {
  94188. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94189. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94190. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94191. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94192. window.removeEventListener("resize", this._onResize);
  94193. document.body.removeChild(VirtualJoystick.vjCanvas);
  94194. VirtualJoystick.vjCanvas = null;
  94195. }
  94196. };
  94197. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94198. VirtualJoystick._globalJoystickIndex = 0;
  94199. return VirtualJoystick;
  94200. }());
  94201. BABYLON.VirtualJoystick = VirtualJoystick;
  94202. })(BABYLON || (BABYLON = {}));
  94203. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94204. var BABYLON;
  94205. (function (BABYLON) {
  94206. // We're mainly based on the logic defined into the FreeCamera code
  94207. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94208. __extends(VirtualJoysticksCamera, _super);
  94209. function VirtualJoysticksCamera(name, position, scene) {
  94210. var _this = _super.call(this, name, position, scene) || this;
  94211. _this.inputs.addVirtualJoystick();
  94212. return _this;
  94213. }
  94214. VirtualJoysticksCamera.prototype.getClassName = function () {
  94215. return "VirtualJoysticksCamera";
  94216. };
  94217. return VirtualJoysticksCamera;
  94218. }(BABYLON.FreeCamera));
  94219. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94220. })(BABYLON || (BABYLON = {}));
  94221. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94222. var BABYLON;
  94223. (function (BABYLON) {
  94224. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94225. function FreeCameraVirtualJoystickInput() {
  94226. }
  94227. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94228. return this._leftjoystick;
  94229. };
  94230. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94231. return this._rightjoystick;
  94232. };
  94233. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94234. if (this._leftjoystick) {
  94235. var camera = this.camera;
  94236. var speed = camera._computeLocalCameraSpeed() * 50;
  94237. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94238. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94239. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94240. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94241. if (!this._leftjoystick.pressed) {
  94242. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94243. }
  94244. if (!this._rightjoystick.pressed) {
  94245. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94246. }
  94247. }
  94248. };
  94249. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94250. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94251. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94252. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94253. this._leftjoystick.setJoystickSensibility(0.15);
  94254. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94255. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94256. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94257. this._rightjoystick.reverseUpDown = true;
  94258. this._rightjoystick.setJoystickSensibility(0.05);
  94259. this._rightjoystick.setJoystickColor("yellow");
  94260. };
  94261. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94262. this._leftjoystick.releaseCanvas();
  94263. this._rightjoystick.releaseCanvas();
  94264. };
  94265. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94266. return "FreeCameraVirtualJoystickInput";
  94267. };
  94268. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94269. return "virtualJoystick";
  94270. };
  94271. return FreeCameraVirtualJoystickInput;
  94272. }());
  94273. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94274. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94275. })(BABYLON || (BABYLON = {}));
  94276. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94277. var BABYLON;
  94278. (function (BABYLON) {
  94279. var SimplificationSettings = /** @class */ (function () {
  94280. function SimplificationSettings(quality, distance, optimizeMesh) {
  94281. this.quality = quality;
  94282. this.distance = distance;
  94283. this.optimizeMesh = optimizeMesh;
  94284. }
  94285. return SimplificationSettings;
  94286. }());
  94287. BABYLON.SimplificationSettings = SimplificationSettings;
  94288. var SimplificationQueue = /** @class */ (function () {
  94289. function SimplificationQueue() {
  94290. this.running = false;
  94291. this._simplificationArray = [];
  94292. }
  94293. SimplificationQueue.prototype.addTask = function (task) {
  94294. this._simplificationArray.push(task);
  94295. };
  94296. SimplificationQueue.prototype.executeNext = function () {
  94297. var task = this._simplificationArray.pop();
  94298. if (task) {
  94299. this.running = true;
  94300. this.runSimplification(task);
  94301. }
  94302. else {
  94303. this.running = false;
  94304. }
  94305. };
  94306. SimplificationQueue.prototype.runSimplification = function (task) {
  94307. var _this = this;
  94308. if (task.parallelProcessing) {
  94309. //parallel simplifier
  94310. task.settings.forEach(function (setting) {
  94311. var simplifier = _this.getSimplifier(task);
  94312. simplifier.simplify(setting, function (newMesh) {
  94313. task.mesh.addLODLevel(setting.distance, newMesh);
  94314. newMesh.isVisible = true;
  94315. //check if it is the last
  94316. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94317. //all done, run the success callback.
  94318. task.successCallback();
  94319. }
  94320. _this.executeNext();
  94321. });
  94322. });
  94323. }
  94324. else {
  94325. //single simplifier.
  94326. var simplifier = this.getSimplifier(task);
  94327. var runDecimation = function (setting, callback) {
  94328. simplifier.simplify(setting, function (newMesh) {
  94329. task.mesh.addLODLevel(setting.distance, newMesh);
  94330. newMesh.isVisible = true;
  94331. //run the next quality level
  94332. callback();
  94333. });
  94334. };
  94335. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94336. runDecimation(task.settings[loop.index], function () {
  94337. loop.executeNext();
  94338. });
  94339. }, function () {
  94340. //execution ended, run the success callback.
  94341. if (task.successCallback) {
  94342. task.successCallback();
  94343. }
  94344. _this.executeNext();
  94345. });
  94346. }
  94347. };
  94348. SimplificationQueue.prototype.getSimplifier = function (task) {
  94349. switch (task.simplificationType) {
  94350. case SimplificationType.QUADRATIC:
  94351. default:
  94352. return new QuadraticErrorSimplification(task.mesh);
  94353. }
  94354. };
  94355. return SimplificationQueue;
  94356. }());
  94357. BABYLON.SimplificationQueue = SimplificationQueue;
  94358. /**
  94359. * The implemented types of simplification
  94360. * At the moment only Quadratic Error Decimation is implemented
  94361. */
  94362. var SimplificationType;
  94363. (function (SimplificationType) {
  94364. /** Quadratic error decimation */
  94365. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94366. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94367. var DecimationTriangle = /** @class */ (function () {
  94368. function DecimationTriangle(vertices) {
  94369. this.vertices = vertices;
  94370. this.error = new Array(4);
  94371. this.deleted = false;
  94372. this.isDirty = false;
  94373. this.deletePending = false;
  94374. this.borderFactor = 0;
  94375. }
  94376. return DecimationTriangle;
  94377. }());
  94378. BABYLON.DecimationTriangle = DecimationTriangle;
  94379. var DecimationVertex = /** @class */ (function () {
  94380. function DecimationVertex(position, id) {
  94381. this.position = position;
  94382. this.id = id;
  94383. this.isBorder = true;
  94384. this.q = new QuadraticMatrix();
  94385. this.triangleCount = 0;
  94386. this.triangleStart = 0;
  94387. this.originalOffsets = [];
  94388. }
  94389. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94390. this.position.copyFrom(newPosition);
  94391. };
  94392. return DecimationVertex;
  94393. }());
  94394. BABYLON.DecimationVertex = DecimationVertex;
  94395. var QuadraticMatrix = /** @class */ (function () {
  94396. function QuadraticMatrix(data) {
  94397. this.data = new Array(10);
  94398. for (var i = 0; i < 10; ++i) {
  94399. if (data && data[i]) {
  94400. this.data[i] = data[i];
  94401. }
  94402. else {
  94403. this.data[i] = 0;
  94404. }
  94405. }
  94406. }
  94407. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94408. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94409. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94410. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94411. return det;
  94412. };
  94413. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94414. for (var i = 0; i < 10; ++i) {
  94415. this.data[i] += matrix.data[i];
  94416. }
  94417. };
  94418. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94419. for (var i = 0; i < 10; ++i) {
  94420. this.data[i] += data[i];
  94421. }
  94422. };
  94423. QuadraticMatrix.prototype.add = function (matrix) {
  94424. var m = new QuadraticMatrix();
  94425. for (var i = 0; i < 10; ++i) {
  94426. m.data[i] = this.data[i] + matrix.data[i];
  94427. }
  94428. return m;
  94429. };
  94430. QuadraticMatrix.FromData = function (a, b, c, d) {
  94431. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94432. };
  94433. //returning an array to avoid garbage collection
  94434. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94435. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94436. };
  94437. return QuadraticMatrix;
  94438. }());
  94439. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94440. var Reference = /** @class */ (function () {
  94441. function Reference(vertexId, triangleId) {
  94442. this.vertexId = vertexId;
  94443. this.triangleId = triangleId;
  94444. }
  94445. return Reference;
  94446. }());
  94447. BABYLON.Reference = Reference;
  94448. /**
  94449. * An implementation of the Quadratic Error simplification algorithm.
  94450. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94451. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94452. * @author RaananW
  94453. */
  94454. var QuadraticErrorSimplification = /** @class */ (function () {
  94455. function QuadraticErrorSimplification(_mesh) {
  94456. this._mesh = _mesh;
  94457. this.syncIterations = 5000;
  94458. this.aggressiveness = 7;
  94459. this.decimationIterations = 100;
  94460. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94461. }
  94462. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94463. var _this = this;
  94464. this.initDecimatedMesh();
  94465. //iterating through the submeshes array, one after the other.
  94466. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94467. _this.initWithMesh(loop.index, function () {
  94468. _this.runDecimation(settings, loop.index, function () {
  94469. loop.executeNext();
  94470. });
  94471. }, settings.optimizeMesh);
  94472. }, function () {
  94473. setTimeout(function () {
  94474. successCallback(_this._reconstructedMesh);
  94475. }, 0);
  94476. });
  94477. };
  94478. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94479. var _this = this;
  94480. var targetCount = ~~(this.triangles.length * settings.quality);
  94481. var deletedTriangles = 0;
  94482. var triangleCount = this.triangles.length;
  94483. var iterationFunction = function (iteration, callback) {
  94484. setTimeout(function () {
  94485. if (iteration % 5 === 0) {
  94486. _this.updateMesh(iteration === 0);
  94487. }
  94488. for (var i = 0; i < _this.triangles.length; ++i) {
  94489. _this.triangles[i].isDirty = false;
  94490. }
  94491. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94492. var trianglesIterator = function (i) {
  94493. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94494. var t = _this.triangles[tIdx];
  94495. if (!t)
  94496. return;
  94497. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94498. return;
  94499. }
  94500. for (var j = 0; j < 3; ++j) {
  94501. if (t.error[j] < threshold) {
  94502. var deleted0 = [];
  94503. var deleted1 = [];
  94504. var v0 = t.vertices[j];
  94505. var v1 = t.vertices[(j + 1) % 3];
  94506. if (v0.isBorder || v1.isBorder)
  94507. continue;
  94508. var p = BABYLON.Vector3.Zero();
  94509. var n = BABYLON.Vector3.Zero();
  94510. var uv = BABYLON.Vector2.Zero();
  94511. var color = new BABYLON.Color4(0, 0, 0, 1);
  94512. _this.calculateError(v0, v1, p, n, uv, color);
  94513. var delTr = new Array();
  94514. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94515. continue;
  94516. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94517. continue;
  94518. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94519. continue;
  94520. var uniqueArray = new Array();
  94521. delTr.forEach(function (deletedT) {
  94522. if (uniqueArray.indexOf(deletedT) === -1) {
  94523. deletedT.deletePending = true;
  94524. uniqueArray.push(deletedT);
  94525. }
  94526. });
  94527. if (uniqueArray.length % 2 !== 0) {
  94528. continue;
  94529. }
  94530. v0.q = v1.q.add(v0.q);
  94531. v0.updatePosition(p);
  94532. var tStart = _this.references.length;
  94533. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94534. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94535. var tCount = _this.references.length - tStart;
  94536. if (tCount <= v0.triangleCount) {
  94537. if (tCount) {
  94538. for (var c = 0; c < tCount; c++) {
  94539. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94540. }
  94541. }
  94542. }
  94543. else {
  94544. v0.triangleStart = tStart;
  94545. }
  94546. v0.triangleCount = tCount;
  94547. break;
  94548. }
  94549. }
  94550. };
  94551. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94552. }, 0);
  94553. };
  94554. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94555. if (triangleCount - deletedTriangles <= targetCount)
  94556. loop.breakLoop();
  94557. else {
  94558. iterationFunction(loop.index, function () {
  94559. loop.executeNext();
  94560. });
  94561. }
  94562. }, function () {
  94563. setTimeout(function () {
  94564. //reconstruct this part of the mesh
  94565. _this.reconstructMesh(submeshIndex);
  94566. successCallback();
  94567. }, 0);
  94568. });
  94569. };
  94570. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94571. var _this = this;
  94572. this.vertices = [];
  94573. this.triangles = [];
  94574. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94575. var indices = this._mesh.getIndices();
  94576. var submesh = this._mesh.subMeshes[submeshIndex];
  94577. var findInVertices = function (positionToSearch) {
  94578. if (optimizeMesh) {
  94579. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94580. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94581. return _this.vertices[ii];
  94582. }
  94583. }
  94584. }
  94585. return null;
  94586. };
  94587. var vertexReferences = [];
  94588. var vertexInit = function (i) {
  94589. if (!positionData) {
  94590. return;
  94591. }
  94592. var offset = i + submesh.verticesStart;
  94593. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94594. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94595. vertex.originalOffsets.push(offset);
  94596. if (vertex.id === _this.vertices.length) {
  94597. _this.vertices.push(vertex);
  94598. }
  94599. vertexReferences.push(vertex.id);
  94600. };
  94601. //var totalVertices = mesh.getTotalVertices();
  94602. var totalVertices = submesh.verticesCount;
  94603. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94604. var indicesInit = function (i) {
  94605. if (!indices) {
  94606. return;
  94607. }
  94608. var offset = (submesh.indexStart / 3) + i;
  94609. var pos = (offset * 3);
  94610. var i0 = indices[pos + 0];
  94611. var i1 = indices[pos + 1];
  94612. var i2 = indices[pos + 2];
  94613. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94614. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94615. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94616. var triangle = new DecimationTriangle([v0, v1, v2]);
  94617. triangle.originalOffset = pos;
  94618. _this.triangles.push(triangle);
  94619. };
  94620. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94621. _this.init(callback);
  94622. });
  94623. });
  94624. };
  94625. QuadraticErrorSimplification.prototype.init = function (callback) {
  94626. var _this = this;
  94627. var triangleInit1 = function (i) {
  94628. var t = _this.triangles[i];
  94629. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94630. for (var j = 0; j < 3; j++) {
  94631. 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))));
  94632. }
  94633. };
  94634. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94635. var triangleInit2 = function (i) {
  94636. var t = _this.triangles[i];
  94637. for (var j = 0; j < 3; ++j) {
  94638. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94639. }
  94640. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94641. };
  94642. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94643. callback();
  94644. });
  94645. });
  94646. };
  94647. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94648. var newTriangles = [];
  94649. var i;
  94650. for (i = 0; i < this.vertices.length; ++i) {
  94651. this.vertices[i].triangleCount = 0;
  94652. }
  94653. var t;
  94654. var j;
  94655. for (i = 0; i < this.triangles.length; ++i) {
  94656. if (!this.triangles[i].deleted) {
  94657. t = this.triangles[i];
  94658. for (j = 0; j < 3; ++j) {
  94659. t.vertices[j].triangleCount = 1;
  94660. }
  94661. newTriangles.push(t);
  94662. }
  94663. }
  94664. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94665. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94666. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94667. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94668. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94669. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94670. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94671. var vertexCount = 0;
  94672. for (i = 0; i < this.vertices.length; ++i) {
  94673. var vertex = this.vertices[i];
  94674. vertex.id = vertexCount;
  94675. if (vertex.triangleCount) {
  94676. vertex.originalOffsets.forEach(function (originalOffset) {
  94677. if (!normalData) {
  94678. return;
  94679. }
  94680. newPositionData.push(vertex.position.x);
  94681. newPositionData.push(vertex.position.y);
  94682. newPositionData.push(vertex.position.z);
  94683. newNormalData.push(normalData[originalOffset * 3]);
  94684. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94685. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94686. if (uvs && uvs.length) {
  94687. newUVsData.push(uvs[(originalOffset * 2)]);
  94688. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94689. }
  94690. else if (colorsData && colorsData.length) {
  94691. newColorsData.push(colorsData[(originalOffset * 4)]);
  94692. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94693. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94694. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94695. }
  94696. ++vertexCount;
  94697. });
  94698. }
  94699. }
  94700. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94701. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94702. var submeshesArray = this._reconstructedMesh.subMeshes;
  94703. this._reconstructedMesh.subMeshes = [];
  94704. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94705. var originalIndices = this._mesh.getIndices();
  94706. for (i = 0; i < newTriangles.length; ++i) {
  94707. t = newTriangles[i]; //now get the new referencing point for each vertex
  94708. [0, 1, 2].forEach(function (idx) {
  94709. var id = originalIndices[t.originalOffset + idx];
  94710. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94711. if (offset < 0)
  94712. offset = 0;
  94713. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94714. });
  94715. }
  94716. //overwriting the old vertex buffers and indices.
  94717. this._reconstructedMesh.setIndices(newIndicesArray);
  94718. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94719. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94720. if (newUVsData.length > 0)
  94721. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94722. if (newColorsData.length > 0)
  94723. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94724. //create submesh
  94725. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94726. if (submeshIndex > 0) {
  94727. this._reconstructedMesh.subMeshes = [];
  94728. submeshesArray.forEach(function (submesh) {
  94729. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94730. });
  94731. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94732. }
  94733. };
  94734. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94735. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94736. this._reconstructedMesh.material = this._mesh.material;
  94737. this._reconstructedMesh.parent = this._mesh.parent;
  94738. this._reconstructedMesh.isVisible = false;
  94739. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94740. };
  94741. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94742. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94743. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94744. if (t.deleted)
  94745. continue;
  94746. var s = this.references[vertex1.triangleStart + i].vertexId;
  94747. var v1 = t.vertices[(s + 1) % 3];
  94748. var v2 = t.vertices[(s + 2) % 3];
  94749. if ((v1 === vertex2 || v2 === vertex2)) {
  94750. deletedArray[i] = true;
  94751. delTr.push(t);
  94752. continue;
  94753. }
  94754. var d1 = v1.position.subtract(point);
  94755. d1 = d1.normalize();
  94756. var d2 = v2.position.subtract(point);
  94757. d2 = d2.normalize();
  94758. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94759. return true;
  94760. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94761. deletedArray[i] = false;
  94762. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94763. return true;
  94764. }
  94765. return false;
  94766. };
  94767. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94768. var newDeleted = deletedTriangles;
  94769. for (var i = 0; i < vertex.triangleCount; ++i) {
  94770. var ref = this.references[vertex.triangleStart + i];
  94771. var t = this.triangles[ref.triangleId];
  94772. if (t.deleted)
  94773. continue;
  94774. if (deletedArray[i] && t.deletePending) {
  94775. t.deleted = true;
  94776. newDeleted++;
  94777. continue;
  94778. }
  94779. t.vertices[ref.vertexId] = origVertex;
  94780. t.isDirty = true;
  94781. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94782. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94783. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94784. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94785. this.references.push(ref);
  94786. }
  94787. return newDeleted;
  94788. };
  94789. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94790. for (var i = 0; i < this.vertices.length; ++i) {
  94791. var vCount = [];
  94792. var vId = [];
  94793. var v = this.vertices[i];
  94794. var j;
  94795. for (j = 0; j < v.triangleCount; ++j) {
  94796. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94797. for (var ii = 0; ii < 3; ii++) {
  94798. var ofs = 0;
  94799. var vv = triangle.vertices[ii];
  94800. while (ofs < vCount.length) {
  94801. if (vId[ofs] === vv.id)
  94802. break;
  94803. ++ofs;
  94804. }
  94805. if (ofs === vCount.length) {
  94806. vCount.push(1);
  94807. vId.push(vv.id);
  94808. }
  94809. else {
  94810. vCount[ofs]++;
  94811. }
  94812. }
  94813. }
  94814. for (j = 0; j < vCount.length; ++j) {
  94815. if (vCount[j] === 1) {
  94816. this.vertices[vId[j]].isBorder = true;
  94817. }
  94818. else {
  94819. this.vertices[vId[j]].isBorder = false;
  94820. }
  94821. }
  94822. }
  94823. };
  94824. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94825. if (identifyBorders === void 0) { identifyBorders = false; }
  94826. var i;
  94827. if (!identifyBorders) {
  94828. var newTrianglesVector = [];
  94829. for (i = 0; i < this.triangles.length; ++i) {
  94830. if (!this.triangles[i].deleted) {
  94831. newTrianglesVector.push(this.triangles[i]);
  94832. }
  94833. }
  94834. this.triangles = newTrianglesVector;
  94835. }
  94836. for (i = 0; i < this.vertices.length; ++i) {
  94837. this.vertices[i].triangleCount = 0;
  94838. this.vertices[i].triangleStart = 0;
  94839. }
  94840. var t;
  94841. var j;
  94842. var v;
  94843. for (i = 0; i < this.triangles.length; ++i) {
  94844. t = this.triangles[i];
  94845. for (j = 0; j < 3; ++j) {
  94846. v = t.vertices[j];
  94847. v.triangleCount++;
  94848. }
  94849. }
  94850. var tStart = 0;
  94851. for (i = 0; i < this.vertices.length; ++i) {
  94852. this.vertices[i].triangleStart = tStart;
  94853. tStart += this.vertices[i].triangleCount;
  94854. this.vertices[i].triangleCount = 0;
  94855. }
  94856. var newReferences = new Array(this.triangles.length * 3);
  94857. for (i = 0; i < this.triangles.length; ++i) {
  94858. t = this.triangles[i];
  94859. for (j = 0; j < 3; ++j) {
  94860. v = t.vertices[j];
  94861. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94862. v.triangleCount++;
  94863. }
  94864. }
  94865. this.references = newReferences;
  94866. if (identifyBorders) {
  94867. this.identifyBorder();
  94868. }
  94869. };
  94870. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94871. var x = point.x;
  94872. var y = point.y;
  94873. var z = point.z;
  94874. 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
  94875. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94876. };
  94877. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94878. var q = vertex1.q.add(vertex2.q);
  94879. var border = vertex1.isBorder && vertex2.isBorder;
  94880. var error = 0;
  94881. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94882. if (qDet !== 0 && !border) {
  94883. if (!pointResult) {
  94884. pointResult = BABYLON.Vector3.Zero();
  94885. }
  94886. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94887. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94888. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94889. error = this.vertexError(q, pointResult);
  94890. }
  94891. else {
  94892. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94893. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94894. var error1 = this.vertexError(q, vertex1.position);
  94895. var error2 = this.vertexError(q, vertex2.position);
  94896. var error3 = this.vertexError(q, p3);
  94897. error = Math.min(error1, error2, error3);
  94898. if (error === error1) {
  94899. if (pointResult) {
  94900. pointResult.copyFrom(vertex1.position);
  94901. }
  94902. }
  94903. else if (error === error2) {
  94904. if (pointResult) {
  94905. pointResult.copyFrom(vertex2.position);
  94906. }
  94907. }
  94908. else {
  94909. if (pointResult) {
  94910. pointResult.copyFrom(p3);
  94911. }
  94912. }
  94913. }
  94914. return error;
  94915. };
  94916. return QuadraticErrorSimplification;
  94917. }());
  94918. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94919. })(BABYLON || (BABYLON = {}));
  94920. //# sourceMappingURL=babylon.meshSimplification.js.map
  94921. var BABYLON;
  94922. (function (BABYLON) {
  94923. var MeshLODLevel = /** @class */ (function () {
  94924. function MeshLODLevel(distance, mesh) {
  94925. this.distance = distance;
  94926. this.mesh = mesh;
  94927. }
  94928. return MeshLODLevel;
  94929. }());
  94930. BABYLON.MeshLODLevel = MeshLODLevel;
  94931. })(BABYLON || (BABYLON = {}));
  94932. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94933. var BABYLON;
  94934. (function (BABYLON) {
  94935. /**
  94936. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94937. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94938. */
  94939. var SceneOptimization = /** @class */ (function () {
  94940. /**
  94941. * Creates the SceneOptimization object
  94942. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94943. * @param desc defines the description associated with the optimization
  94944. */
  94945. function SceneOptimization(
  94946. /**
  94947. * Defines the priority of this optimization (0 by default which means first in the list)
  94948. */
  94949. priority) {
  94950. if (priority === void 0) { priority = 0; }
  94951. this.priority = priority;
  94952. }
  94953. /**
  94954. * Gets a string describing the action executed by the current optimization
  94955. * @returns description string
  94956. */
  94957. SceneOptimization.prototype.getDescription = function () {
  94958. return "";
  94959. };
  94960. /**
  94961. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94962. * @param scene defines the current scene where to apply this optimization
  94963. * @param optimizer defines the current optimizer
  94964. * @returns true if everything that can be done was applied
  94965. */
  94966. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94967. return true;
  94968. };
  94969. ;
  94970. return SceneOptimization;
  94971. }());
  94972. BABYLON.SceneOptimization = SceneOptimization;
  94973. /**
  94974. * Defines an optimization used to reduce the size of render target textures
  94975. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94976. */
  94977. var TextureOptimization = /** @class */ (function (_super) {
  94978. __extends(TextureOptimization, _super);
  94979. /**
  94980. * Creates the TextureOptimization object
  94981. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94982. * @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
  94983. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94984. */
  94985. function TextureOptimization(
  94986. /**
  94987. * Defines the priority of this optimization (0 by default which means first in the list)
  94988. */
  94989. priority,
  94990. /**
  94991. * 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
  94992. */
  94993. maximumSize,
  94994. /**
  94995. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94996. */
  94997. step) {
  94998. if (priority === void 0) { priority = 0; }
  94999. if (maximumSize === void 0) { maximumSize = 1024; }
  95000. if (step === void 0) { step = 0.5; }
  95001. var _this = _super.call(this, priority) || this;
  95002. _this.priority = priority;
  95003. _this.maximumSize = maximumSize;
  95004. _this.step = step;
  95005. return _this;
  95006. }
  95007. /**
  95008. * Gets a string describing the action executed by the current optimization
  95009. * @returns description string
  95010. */
  95011. TextureOptimization.prototype.getDescription = function () {
  95012. return "Reducing render target texture size to " + this.maximumSize;
  95013. };
  95014. /**
  95015. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95016. * @param scene defines the current scene where to apply this optimization
  95017. * @param optimizer defines the current optimizer
  95018. * @returns true if everything that can be done was applied
  95019. */
  95020. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95021. var allDone = true;
  95022. for (var index = 0; index < scene.textures.length; index++) {
  95023. var texture = scene.textures[index];
  95024. if (!texture.canRescale || texture.getContext) {
  95025. continue;
  95026. }
  95027. var currentSize = texture.getSize();
  95028. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95029. if (maxDimension > this.maximumSize) {
  95030. texture.scale(this.step);
  95031. allDone = false;
  95032. }
  95033. }
  95034. return allDone;
  95035. };
  95036. return TextureOptimization;
  95037. }(SceneOptimization));
  95038. BABYLON.TextureOptimization = TextureOptimization;
  95039. /**
  95040. * Defines an optimization used to increase or decrease the rendering resolution
  95041. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95042. */
  95043. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95044. __extends(HardwareScalingOptimization, _super);
  95045. /**
  95046. * Creates the HardwareScalingOptimization object
  95047. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95048. * @param maximumScale defines the maximum scale to use (2 by default)
  95049. * @param step defines the step to use between two passes (0.5 by default)
  95050. */
  95051. function HardwareScalingOptimization(
  95052. /**
  95053. * Defines the priority of this optimization (0 by default which means first in the list)
  95054. */
  95055. priority,
  95056. /**
  95057. * Defines the maximum scale to use (2 by default)
  95058. */
  95059. maximumScale,
  95060. /**
  95061. * Defines the step to use between two passes (0.5 by default)
  95062. */
  95063. step) {
  95064. if (priority === void 0) { priority = 0; }
  95065. if (maximumScale === void 0) { maximumScale = 2; }
  95066. if (step === void 0) { step = 0.25; }
  95067. var _this = _super.call(this, priority) || this;
  95068. _this.priority = priority;
  95069. _this.maximumScale = maximumScale;
  95070. _this.step = step;
  95071. _this._currentScale = -1;
  95072. _this._directionOffset = 1;
  95073. return _this;
  95074. }
  95075. /**
  95076. * Gets a string describing the action executed by the current optimization
  95077. * @return description string
  95078. */
  95079. HardwareScalingOptimization.prototype.getDescription = function () {
  95080. return "Setting hardware scaling level to " + this._currentScale;
  95081. };
  95082. /**
  95083. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95084. * @param scene defines the current scene where to apply this optimization
  95085. * @param optimizer defines the current optimizer
  95086. * @returns true if everything that can be done was applied
  95087. */
  95088. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95089. if (this._currentScale === -1) {
  95090. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95091. if (this._currentScale > this.maximumScale) {
  95092. this._directionOffset = -1;
  95093. }
  95094. }
  95095. this._currentScale += this._directionOffset * this.step;
  95096. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95097. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95098. };
  95099. ;
  95100. return HardwareScalingOptimization;
  95101. }(SceneOptimization));
  95102. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95103. /**
  95104. * Defines an optimization used to remove shadows
  95105. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95106. */
  95107. var ShadowsOptimization = /** @class */ (function (_super) {
  95108. __extends(ShadowsOptimization, _super);
  95109. function ShadowsOptimization() {
  95110. return _super !== null && _super.apply(this, arguments) || this;
  95111. }
  95112. /**
  95113. * Gets a string describing the action executed by the current optimization
  95114. * @return description string
  95115. */
  95116. ShadowsOptimization.prototype.getDescription = function () {
  95117. return "Turning shadows on/off";
  95118. };
  95119. /**
  95120. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95121. * @param scene defines the current scene where to apply this optimization
  95122. * @param optimizer defines the current optimizer
  95123. * @returns true if everything that can be done was applied
  95124. */
  95125. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95126. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95127. return true;
  95128. };
  95129. ;
  95130. return ShadowsOptimization;
  95131. }(SceneOptimization));
  95132. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95133. /**
  95134. * Defines an optimization used to turn post-processes off
  95135. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95136. */
  95137. var PostProcessesOptimization = /** @class */ (function (_super) {
  95138. __extends(PostProcessesOptimization, _super);
  95139. function PostProcessesOptimization() {
  95140. return _super !== null && _super.apply(this, arguments) || this;
  95141. }
  95142. /**
  95143. * Gets a string describing the action executed by the current optimization
  95144. * @return description string
  95145. */
  95146. PostProcessesOptimization.prototype.getDescription = function () {
  95147. return "Turning post-processes on/off";
  95148. };
  95149. /**
  95150. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95151. * @param scene defines the current scene where to apply this optimization
  95152. * @param optimizer defines the current optimizer
  95153. * @returns true if everything that can be done was applied
  95154. */
  95155. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95156. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95157. return true;
  95158. };
  95159. ;
  95160. return PostProcessesOptimization;
  95161. }(SceneOptimization));
  95162. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95163. /**
  95164. * Defines an optimization used to turn lens flares off
  95165. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95166. */
  95167. var LensFlaresOptimization = /** @class */ (function (_super) {
  95168. __extends(LensFlaresOptimization, _super);
  95169. function LensFlaresOptimization() {
  95170. return _super !== null && _super.apply(this, arguments) || this;
  95171. }
  95172. /**
  95173. * Gets a string describing the action executed by the current optimization
  95174. * @return description string
  95175. */
  95176. LensFlaresOptimization.prototype.getDescription = function () {
  95177. return "Turning lens flares on/off";
  95178. };
  95179. /**
  95180. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95181. * @param scene defines the current scene where to apply this optimization
  95182. * @param optimizer defines the current optimizer
  95183. * @returns true if everything that can be done was applied
  95184. */
  95185. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95186. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95187. return true;
  95188. };
  95189. ;
  95190. return LensFlaresOptimization;
  95191. }(SceneOptimization));
  95192. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95193. /**
  95194. * Defines an optimization based on user defined callback.
  95195. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95196. */
  95197. var CustomOptimization = /** @class */ (function (_super) {
  95198. __extends(CustomOptimization, _super);
  95199. function CustomOptimization() {
  95200. return _super !== null && _super.apply(this, arguments) || this;
  95201. }
  95202. /**
  95203. * Gets a string describing the action executed by the current optimization
  95204. * @returns description string
  95205. */
  95206. CustomOptimization.prototype.getDescription = function () {
  95207. if (this.onGetDescription) {
  95208. return this.onGetDescription();
  95209. }
  95210. return "Running user defined callback";
  95211. };
  95212. /**
  95213. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95214. * @param scene defines the current scene where to apply this optimization
  95215. * @param optimizer defines the current optimizer
  95216. * @returns true if everything that can be done was applied
  95217. */
  95218. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95219. if (this.onApply) {
  95220. return this.onApply(scene, optimizer);
  95221. }
  95222. return true;
  95223. };
  95224. ;
  95225. return CustomOptimization;
  95226. }(SceneOptimization));
  95227. BABYLON.CustomOptimization = CustomOptimization;
  95228. /**
  95229. * Defines an optimization used to turn particles off
  95230. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95231. */
  95232. var ParticlesOptimization = /** @class */ (function (_super) {
  95233. __extends(ParticlesOptimization, _super);
  95234. function ParticlesOptimization() {
  95235. return _super !== null && _super.apply(this, arguments) || this;
  95236. }
  95237. /**
  95238. * Gets a string describing the action executed by the current optimization
  95239. * @return description string
  95240. */
  95241. ParticlesOptimization.prototype.getDescription = function () {
  95242. return "Turning particles on/off";
  95243. };
  95244. /**
  95245. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95246. * @param scene defines the current scene where to apply this optimization
  95247. * @param optimizer defines the current optimizer
  95248. * @returns true if everything that can be done was applied
  95249. */
  95250. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95251. scene.particlesEnabled = optimizer.isInImprovementMode;
  95252. return true;
  95253. };
  95254. ;
  95255. return ParticlesOptimization;
  95256. }(SceneOptimization));
  95257. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95258. /**
  95259. * Defines an optimization used to turn render targets off
  95260. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95261. */
  95262. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95263. __extends(RenderTargetsOptimization, _super);
  95264. function RenderTargetsOptimization() {
  95265. return _super !== null && _super.apply(this, arguments) || this;
  95266. }
  95267. /**
  95268. * Gets a string describing the action executed by the current optimization
  95269. * @return description string
  95270. */
  95271. RenderTargetsOptimization.prototype.getDescription = function () {
  95272. return "Turning render targets off";
  95273. };
  95274. /**
  95275. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95276. * @param scene defines the current scene where to apply this optimization
  95277. * @param optimizer defines the current optimizer
  95278. * @returns true if everything that can be done was applied
  95279. */
  95280. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95281. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95282. return true;
  95283. };
  95284. ;
  95285. return RenderTargetsOptimization;
  95286. }(SceneOptimization));
  95287. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95288. /**
  95289. * Defines an optimization used to merge meshes with compatible materials
  95290. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95291. */
  95292. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95293. __extends(MergeMeshesOptimization, _super);
  95294. function MergeMeshesOptimization() {
  95295. var _this = _super !== null && _super.apply(this, arguments) || this;
  95296. _this._canBeMerged = function (abstractMesh) {
  95297. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95298. return false;
  95299. }
  95300. var mesh = abstractMesh;
  95301. if (!mesh.isVisible || !mesh.isEnabled()) {
  95302. return false;
  95303. }
  95304. if (mesh.instances.length > 0) {
  95305. return false;
  95306. }
  95307. if (mesh.skeleton || mesh.hasLODLevels) {
  95308. return false;
  95309. }
  95310. if (mesh.parent) {
  95311. return false;
  95312. }
  95313. return true;
  95314. };
  95315. return _this;
  95316. }
  95317. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95318. /**
  95319. * Gets or sets a boolean which defines if optimization octree has to be updated
  95320. */
  95321. get: function () {
  95322. return MergeMeshesOptimization._UpdateSelectionTree;
  95323. },
  95324. /**
  95325. * Gets or sets a boolean which defines if optimization octree has to be updated
  95326. */
  95327. set: function (value) {
  95328. MergeMeshesOptimization._UpdateSelectionTree = value;
  95329. },
  95330. enumerable: true,
  95331. configurable: true
  95332. });
  95333. /**
  95334. * Gets a string describing the action executed by the current optimization
  95335. * @return description string
  95336. */
  95337. MergeMeshesOptimization.prototype.getDescription = function () {
  95338. return "Merging similar meshes together";
  95339. };
  95340. /**
  95341. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95342. * @param scene defines the current scene where to apply this optimization
  95343. * @param optimizer defines the current optimizer
  95344. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95345. * @returns true if everything that can be done was applied
  95346. */
  95347. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95348. var globalPool = scene.meshes.slice(0);
  95349. var globalLength = globalPool.length;
  95350. for (var index = 0; index < globalLength; index++) {
  95351. var currentPool = new Array();
  95352. var current = globalPool[index];
  95353. // Checks
  95354. if (!this._canBeMerged(current)) {
  95355. continue;
  95356. }
  95357. currentPool.push(current);
  95358. // Find compatible meshes
  95359. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95360. var otherMesh = globalPool[subIndex];
  95361. if (!this._canBeMerged(otherMesh)) {
  95362. continue;
  95363. }
  95364. if (otherMesh.material !== current.material) {
  95365. continue;
  95366. }
  95367. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95368. continue;
  95369. }
  95370. currentPool.push(otherMesh);
  95371. globalLength--;
  95372. globalPool.splice(subIndex, 1);
  95373. subIndex--;
  95374. }
  95375. if (currentPool.length < 2) {
  95376. continue;
  95377. }
  95378. // Merge meshes
  95379. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95380. }
  95381. if (updateSelectionTree != undefined) {
  95382. if (updateSelectionTree) {
  95383. scene.createOrUpdateSelectionOctree();
  95384. }
  95385. }
  95386. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95387. scene.createOrUpdateSelectionOctree();
  95388. }
  95389. return true;
  95390. };
  95391. ;
  95392. MergeMeshesOptimization._UpdateSelectionTree = false;
  95393. return MergeMeshesOptimization;
  95394. }(SceneOptimization));
  95395. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95396. /**
  95397. * Defines a list of options used by SceneOptimizer
  95398. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95399. */
  95400. var SceneOptimizerOptions = /** @class */ (function () {
  95401. /**
  95402. * Creates a new list of options used by SceneOptimizer
  95403. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95404. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95405. */
  95406. function SceneOptimizerOptions(
  95407. /**
  95408. * Defines the target frame rate to reach (60 by default)
  95409. */
  95410. targetFrameRate,
  95411. /**
  95412. * Defines the interval between two checkes (2000ms by default)
  95413. */
  95414. trackerDuration) {
  95415. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95416. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95417. this.targetFrameRate = targetFrameRate;
  95418. this.trackerDuration = trackerDuration;
  95419. /**
  95420. * Gets the list of optimizations to apply
  95421. */
  95422. this.optimizations = new Array();
  95423. }
  95424. /**
  95425. * Add a new optimization
  95426. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95427. * @returns the current SceneOptimizerOptions
  95428. */
  95429. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95430. this.optimizations.push(optimization);
  95431. return this;
  95432. };
  95433. /**
  95434. * Add a new custom optimization
  95435. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95436. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95437. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95438. * @returns the current SceneOptimizerOptions
  95439. */
  95440. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95441. if (priority === void 0) { priority = 0; }
  95442. var optimization = new CustomOptimization(priority);
  95443. optimization.onApply = onApply;
  95444. optimization.onGetDescription = onGetDescription;
  95445. this.optimizations.push(optimization);
  95446. return this;
  95447. };
  95448. /**
  95449. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95450. * @param targetFrameRate defines the target frame rate (60 by default)
  95451. * @returns a SceneOptimizerOptions object
  95452. */
  95453. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95454. var result = new SceneOptimizerOptions(targetFrameRate);
  95455. var priority = 0;
  95456. result.addOptimization(new MergeMeshesOptimization(priority));
  95457. result.addOptimization(new ShadowsOptimization(priority));
  95458. result.addOptimization(new LensFlaresOptimization(priority));
  95459. // Next priority
  95460. priority++;
  95461. result.addOptimization(new PostProcessesOptimization(priority));
  95462. result.addOptimization(new ParticlesOptimization(priority));
  95463. // Next priority
  95464. priority++;
  95465. result.addOptimization(new TextureOptimization(priority, 1024));
  95466. return result;
  95467. };
  95468. /**
  95469. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95470. * @param targetFrameRate defines the target frame rate (60 by default)
  95471. * @returns a SceneOptimizerOptions object
  95472. */
  95473. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95474. var result = new SceneOptimizerOptions(targetFrameRate);
  95475. var priority = 0;
  95476. result.addOptimization(new MergeMeshesOptimization(priority));
  95477. result.addOptimization(new ShadowsOptimization(priority));
  95478. result.addOptimization(new LensFlaresOptimization(priority));
  95479. // Next priority
  95480. priority++;
  95481. result.addOptimization(new PostProcessesOptimization(priority));
  95482. result.addOptimization(new ParticlesOptimization(priority));
  95483. // Next priority
  95484. priority++;
  95485. result.addOptimization(new TextureOptimization(priority, 512));
  95486. // Next priority
  95487. priority++;
  95488. result.addOptimization(new RenderTargetsOptimization(priority));
  95489. // Next priority
  95490. priority++;
  95491. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95492. return result;
  95493. };
  95494. /**
  95495. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95496. * @param targetFrameRate defines the target frame rate (60 by default)
  95497. * @returns a SceneOptimizerOptions object
  95498. */
  95499. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95500. var result = new SceneOptimizerOptions(targetFrameRate);
  95501. var priority = 0;
  95502. result.addOptimization(new MergeMeshesOptimization(priority));
  95503. result.addOptimization(new ShadowsOptimization(priority));
  95504. result.addOptimization(new LensFlaresOptimization(priority));
  95505. // Next priority
  95506. priority++;
  95507. result.addOptimization(new PostProcessesOptimization(priority));
  95508. result.addOptimization(new ParticlesOptimization(priority));
  95509. // Next priority
  95510. priority++;
  95511. result.addOptimization(new TextureOptimization(priority, 256));
  95512. // Next priority
  95513. priority++;
  95514. result.addOptimization(new RenderTargetsOptimization(priority));
  95515. // Next priority
  95516. priority++;
  95517. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95518. return result;
  95519. };
  95520. return SceneOptimizerOptions;
  95521. }());
  95522. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95523. /**
  95524. * Class used to run optimizations in order to reach a target frame rate
  95525. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95526. */
  95527. var SceneOptimizer = /** @class */ (function () {
  95528. /**
  95529. * Creates a new SceneOptimizer
  95530. * @param scene defines the scene to work on
  95531. * @param options defines the options to use with the SceneOptimizer
  95532. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95533. * @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)
  95534. */
  95535. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95536. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95537. if (improvementMode === void 0) { improvementMode = false; }
  95538. var _this = this;
  95539. this._isRunning = false;
  95540. this._currentPriorityLevel = 0;
  95541. this._targetFrameRate = 60;
  95542. this._trackerDuration = 2000;
  95543. this._currentFrameRate = 0;
  95544. this._improvementMode = false;
  95545. /**
  95546. * Defines an observable called when the optimizer reaches the target frame rate
  95547. */
  95548. this.onSuccessObservable = new BABYLON.Observable();
  95549. /**
  95550. * Defines an observable called when the optimizer enables an optimization
  95551. */
  95552. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95553. /**
  95554. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95555. */
  95556. this.onFailureObservable = new BABYLON.Observable();
  95557. if (!options) {
  95558. this._options = new SceneOptimizerOptions();
  95559. }
  95560. else {
  95561. this._options = options;
  95562. }
  95563. if (this._options.targetFrameRate) {
  95564. this._targetFrameRate = this._options.targetFrameRate;
  95565. }
  95566. if (this._options.trackerDuration) {
  95567. this._trackerDuration = this._options.trackerDuration;
  95568. }
  95569. if (autoGeneratePriorities) {
  95570. var priority = 0;
  95571. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95572. var optim = _a[_i];
  95573. optim.priority = priority++;
  95574. }
  95575. }
  95576. this._improvementMode = improvementMode;
  95577. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95578. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95579. _this._sceneDisposeObserver = null;
  95580. _this.dispose();
  95581. });
  95582. }
  95583. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95584. /**
  95585. * Gets a boolean indicating if the optimizer is in improvement mode
  95586. */
  95587. get: function () {
  95588. return this._improvementMode;
  95589. },
  95590. enumerable: true,
  95591. configurable: true
  95592. });
  95593. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95594. /**
  95595. * Gets the current priority level (0 at start)
  95596. */
  95597. get: function () {
  95598. return this._currentPriorityLevel;
  95599. },
  95600. enumerable: true,
  95601. configurable: true
  95602. });
  95603. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95604. /**
  95605. * Gets the current frame rate checked by the SceneOptimizer
  95606. */
  95607. get: function () {
  95608. return this._currentFrameRate;
  95609. },
  95610. enumerable: true,
  95611. configurable: true
  95612. });
  95613. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95614. /**
  95615. * Gets or sets the current target frame rate (60 by default)
  95616. */
  95617. get: function () {
  95618. return this._targetFrameRate;
  95619. },
  95620. /**
  95621. * Gets or sets the current target frame rate (60 by default)
  95622. */
  95623. set: function (value) {
  95624. this._targetFrameRate = value;
  95625. },
  95626. enumerable: true,
  95627. configurable: true
  95628. });
  95629. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95630. /**
  95631. * Gets or sets the current interval between two checks (every 2000ms by default)
  95632. */
  95633. get: function () {
  95634. return this._trackerDuration;
  95635. },
  95636. /**
  95637. * Gets or sets the current interval between two checks (every 2000ms by default)
  95638. */
  95639. set: function (value) {
  95640. this._trackerDuration = value;
  95641. },
  95642. enumerable: true,
  95643. configurable: true
  95644. });
  95645. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95646. /**
  95647. * Gets the list of active optimizations
  95648. */
  95649. get: function () {
  95650. return this._options.optimizations;
  95651. },
  95652. enumerable: true,
  95653. configurable: true
  95654. });
  95655. /**
  95656. * Stops the current optimizer
  95657. */
  95658. SceneOptimizer.prototype.stop = function () {
  95659. this._isRunning = false;
  95660. };
  95661. /**
  95662. * Reset the optimizer to initial step (current priority level = 0)
  95663. */
  95664. SceneOptimizer.prototype.reset = function () {
  95665. this._currentPriorityLevel = 0;
  95666. };
  95667. /**
  95668. * Start the optimizer. By default it will try to reach a specific framerate
  95669. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95670. */
  95671. SceneOptimizer.prototype.start = function () {
  95672. var _this = this;
  95673. if (this._isRunning) {
  95674. return;
  95675. }
  95676. this._isRunning = true;
  95677. // Let's wait for the scene to be ready before running our check
  95678. this._scene.executeWhenReady(function () {
  95679. setTimeout(function () {
  95680. _this._checkCurrentState();
  95681. }, _this._trackerDuration);
  95682. });
  95683. };
  95684. SceneOptimizer.prototype._checkCurrentState = function () {
  95685. var _this = this;
  95686. if (!this._isRunning) {
  95687. return;
  95688. }
  95689. var scene = this._scene;
  95690. var options = this._options;
  95691. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95692. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95693. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95694. this._isRunning = false;
  95695. this.onSuccessObservable.notifyObservers(this);
  95696. return;
  95697. }
  95698. // Apply current level of optimizations
  95699. var allDone = true;
  95700. var noOptimizationApplied = true;
  95701. for (var index = 0; index < options.optimizations.length; index++) {
  95702. var optimization = options.optimizations[index];
  95703. if (optimization.priority === this._currentPriorityLevel) {
  95704. noOptimizationApplied = false;
  95705. allDone = allDone && optimization.apply(scene, this);
  95706. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95707. }
  95708. }
  95709. // If no optimization was applied, this is a failure :(
  95710. if (noOptimizationApplied) {
  95711. this._isRunning = false;
  95712. this.onFailureObservable.notifyObservers(this);
  95713. return;
  95714. }
  95715. // If all optimizations were done, move to next level
  95716. if (allDone) {
  95717. this._currentPriorityLevel++;
  95718. }
  95719. // Let's the system running for a specific amount of time before checking FPS
  95720. scene.executeWhenReady(function () {
  95721. setTimeout(function () {
  95722. _this._checkCurrentState();
  95723. }, _this._trackerDuration);
  95724. });
  95725. };
  95726. /**
  95727. * Release all resources
  95728. */
  95729. SceneOptimizer.prototype.dispose = function () {
  95730. this.stop();
  95731. this.onSuccessObservable.clear();
  95732. this.onFailureObservable.clear();
  95733. this.onNewOptimizationAppliedObservable.clear();
  95734. if (this._sceneDisposeObserver) {
  95735. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95736. }
  95737. };
  95738. /**
  95739. * Helper function to create a SceneOptimizer with one single line of code
  95740. * @param scene defines the scene to work on
  95741. * @param options defines the options to use with the SceneOptimizer
  95742. * @param onSuccess defines a callback to call on success
  95743. * @param onFailure defines a callback to call on failure
  95744. * @returns the new SceneOptimizer object
  95745. */
  95746. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95747. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95748. if (onSuccess) {
  95749. optimizer.onSuccessObservable.add(function () {
  95750. onSuccess();
  95751. });
  95752. }
  95753. if (onFailure) {
  95754. optimizer.onFailureObservable.add(function () {
  95755. onFailure();
  95756. });
  95757. }
  95758. optimizer.start();
  95759. return optimizer;
  95760. };
  95761. return SceneOptimizer;
  95762. }());
  95763. BABYLON.SceneOptimizer = SceneOptimizer;
  95764. })(BABYLON || (BABYLON = {}));
  95765. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95766. var BABYLON;
  95767. (function (BABYLON) {
  95768. var OutlineRenderer = /** @class */ (function () {
  95769. function OutlineRenderer(scene) {
  95770. this.zOffset = 1;
  95771. this._scene = scene;
  95772. }
  95773. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95774. var _this = this;
  95775. if (useOverlay === void 0) { useOverlay = false; }
  95776. var scene = this._scene;
  95777. var engine = this._scene.getEngine();
  95778. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95779. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95780. return;
  95781. }
  95782. var mesh = subMesh.getRenderingMesh();
  95783. var material = subMesh.getMaterial();
  95784. if (!material || !scene.activeCamera) {
  95785. return;
  95786. }
  95787. engine.enableEffect(this._effect);
  95788. // Logarithmic depth
  95789. if (material.useLogarithmicDepth) {
  95790. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95791. }
  95792. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95793. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95794. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95795. // Bones
  95796. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95797. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95798. }
  95799. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95800. // Alpha test
  95801. if (material && material.needAlphaTesting()) {
  95802. var alphaTexture = material.getAlphaTestTexture();
  95803. if (alphaTexture) {
  95804. this._effect.setTexture("diffuseSampler", alphaTexture);
  95805. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95806. }
  95807. }
  95808. engine.setZOffset(-this.zOffset);
  95809. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95810. engine.setZOffset(0);
  95811. };
  95812. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95813. var defines = [];
  95814. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95815. var mesh = subMesh.getMesh();
  95816. var material = subMesh.getMaterial();
  95817. if (material) {
  95818. // Alpha test
  95819. if (material.needAlphaTesting()) {
  95820. defines.push("#define ALPHATEST");
  95821. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95822. attribs.push(BABYLON.VertexBuffer.UVKind);
  95823. defines.push("#define UV1");
  95824. }
  95825. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95826. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95827. defines.push("#define UV2");
  95828. }
  95829. }
  95830. //Logarithmic depth
  95831. if (material.useLogarithmicDepth) {
  95832. defines.push("#define LOGARITHMICDEPTH");
  95833. }
  95834. }
  95835. // Bones
  95836. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95839. if (mesh.numBoneInfluencers > 4) {
  95840. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95841. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95842. }
  95843. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95844. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95845. }
  95846. else {
  95847. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95848. }
  95849. // Instances
  95850. if (useInstances) {
  95851. defines.push("#define INSTANCES");
  95852. attribs.push("world0");
  95853. attribs.push("world1");
  95854. attribs.push("world2");
  95855. attribs.push("world3");
  95856. }
  95857. // Get correct effect
  95858. var join = defines.join("\n");
  95859. if (this._cachedDefines !== join) {
  95860. this._cachedDefines = join;
  95861. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95862. }
  95863. return this._effect.isReady();
  95864. };
  95865. return OutlineRenderer;
  95866. }());
  95867. BABYLON.OutlineRenderer = OutlineRenderer;
  95868. })(BABYLON || (BABYLON = {}));
  95869. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95870. var BABYLON;
  95871. (function (BABYLON) {
  95872. var FaceAdjacencies = /** @class */ (function () {
  95873. function FaceAdjacencies() {
  95874. this.edges = new Array();
  95875. this.edgesConnectedCount = 0;
  95876. }
  95877. return FaceAdjacencies;
  95878. }());
  95879. var EdgesRenderer = /** @class */ (function () {
  95880. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95881. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95882. if (epsilon === void 0) { epsilon = 0.95; }
  95883. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95884. this.edgesWidthScalerForOrthographic = 1000.0;
  95885. this.edgesWidthScalerForPerspective = 50.0;
  95886. this._linesPositions = new Array();
  95887. this._linesNormals = new Array();
  95888. this._linesIndices = new Array();
  95889. this._buffers = {};
  95890. this._checkVerticesInsteadOfIndices = false;
  95891. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95892. this.isEnabled = true;
  95893. this._source = source;
  95894. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95895. this._epsilon = epsilon;
  95896. this._prepareRessources();
  95897. this._generateEdgesLines();
  95898. }
  95899. EdgesRenderer.prototype._prepareRessources = function () {
  95900. if (this._lineShader) {
  95901. return;
  95902. }
  95903. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95904. attributes: ["position", "normal"],
  95905. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95906. });
  95907. this._lineShader.disableDepthWrite = true;
  95908. this._lineShader.backFaceCulling = false;
  95909. };
  95910. EdgesRenderer.prototype._rebuild = function () {
  95911. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95912. if (buffer) {
  95913. buffer._rebuild();
  95914. }
  95915. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95916. if (buffer) {
  95917. buffer._rebuild();
  95918. }
  95919. var scene = this._source.getScene();
  95920. var engine = scene.getEngine();
  95921. this._ib = engine.createIndexBuffer(this._linesIndices);
  95922. };
  95923. EdgesRenderer.prototype.dispose = function () {
  95924. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95925. if (buffer) {
  95926. buffer.dispose();
  95927. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95928. }
  95929. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95930. if (buffer) {
  95931. buffer.dispose();
  95932. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95933. }
  95934. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95935. this._lineShader.dispose();
  95936. };
  95937. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95938. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95939. return 0;
  95940. }
  95941. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95942. return 1;
  95943. }
  95944. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95945. return 2;
  95946. }
  95947. return -1;
  95948. };
  95949. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95950. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95951. return 0;
  95952. }
  95953. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95954. return 1;
  95955. }
  95956. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95957. return 2;
  95958. }
  95959. return -1;
  95960. };
  95961. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95962. var needToCreateLine;
  95963. if (edge === undefined) {
  95964. needToCreateLine = true;
  95965. }
  95966. else {
  95967. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95968. needToCreateLine = dotProduct < this._epsilon;
  95969. }
  95970. if (needToCreateLine) {
  95971. var offset = this._linesPositions.length / 3;
  95972. var normal = p0.subtract(p1);
  95973. normal.normalize();
  95974. // Positions
  95975. this._linesPositions.push(p0.x);
  95976. this._linesPositions.push(p0.y);
  95977. this._linesPositions.push(p0.z);
  95978. this._linesPositions.push(p0.x);
  95979. this._linesPositions.push(p0.y);
  95980. this._linesPositions.push(p0.z);
  95981. this._linesPositions.push(p1.x);
  95982. this._linesPositions.push(p1.y);
  95983. this._linesPositions.push(p1.z);
  95984. this._linesPositions.push(p1.x);
  95985. this._linesPositions.push(p1.y);
  95986. this._linesPositions.push(p1.z);
  95987. // Normals
  95988. this._linesNormals.push(p1.x);
  95989. this._linesNormals.push(p1.y);
  95990. this._linesNormals.push(p1.z);
  95991. this._linesNormals.push(-1);
  95992. this._linesNormals.push(p1.x);
  95993. this._linesNormals.push(p1.y);
  95994. this._linesNormals.push(p1.z);
  95995. this._linesNormals.push(1);
  95996. this._linesNormals.push(p0.x);
  95997. this._linesNormals.push(p0.y);
  95998. this._linesNormals.push(p0.z);
  95999. this._linesNormals.push(-1);
  96000. this._linesNormals.push(p0.x);
  96001. this._linesNormals.push(p0.y);
  96002. this._linesNormals.push(p0.z);
  96003. this._linesNormals.push(1);
  96004. // Indices
  96005. this._linesIndices.push(offset);
  96006. this._linesIndices.push(offset + 1);
  96007. this._linesIndices.push(offset + 2);
  96008. this._linesIndices.push(offset);
  96009. this._linesIndices.push(offset + 2);
  96010. this._linesIndices.push(offset + 3);
  96011. }
  96012. };
  96013. EdgesRenderer.prototype._generateEdgesLines = function () {
  96014. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96015. var indices = this._source.getIndices();
  96016. if (!indices || !positions) {
  96017. return;
  96018. }
  96019. // First let's find adjacencies
  96020. var adjacencies = new Array();
  96021. var faceNormals = new Array();
  96022. var index;
  96023. var faceAdjacencies;
  96024. // Prepare faces
  96025. for (index = 0; index < indices.length; index += 3) {
  96026. faceAdjacencies = new FaceAdjacencies();
  96027. var p0Index = indices[index];
  96028. var p1Index = indices[index + 1];
  96029. var p2Index = indices[index + 2];
  96030. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96031. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96032. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96033. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96034. faceNormal.normalize();
  96035. faceNormals.push(faceNormal);
  96036. adjacencies.push(faceAdjacencies);
  96037. }
  96038. // Scan
  96039. for (index = 0; index < adjacencies.length; index++) {
  96040. faceAdjacencies = adjacencies[index];
  96041. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96042. var otherFaceAdjacencies = adjacencies[otherIndex];
  96043. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96044. break;
  96045. }
  96046. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96047. continue;
  96048. }
  96049. var otherP0 = indices[otherIndex * 3];
  96050. var otherP1 = indices[otherIndex * 3 + 1];
  96051. var otherP2 = indices[otherIndex * 3 + 2];
  96052. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96053. var otherEdgeIndex = 0;
  96054. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96055. continue;
  96056. }
  96057. switch (edgeIndex) {
  96058. case 0:
  96059. if (this._checkVerticesInsteadOfIndices) {
  96060. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96061. }
  96062. else {
  96063. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96064. }
  96065. break;
  96066. case 1:
  96067. if (this._checkVerticesInsteadOfIndices) {
  96068. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96069. }
  96070. else {
  96071. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96072. }
  96073. break;
  96074. case 2:
  96075. if (this._checkVerticesInsteadOfIndices) {
  96076. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96077. }
  96078. else {
  96079. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96080. }
  96081. break;
  96082. }
  96083. if (otherEdgeIndex === -1) {
  96084. continue;
  96085. }
  96086. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96087. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96088. faceAdjacencies.edgesConnectedCount++;
  96089. otherFaceAdjacencies.edgesConnectedCount++;
  96090. if (faceAdjacencies.edgesConnectedCount === 3) {
  96091. break;
  96092. }
  96093. }
  96094. }
  96095. }
  96096. // Create lines
  96097. for (index = 0; index < adjacencies.length; index++) {
  96098. // 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
  96099. var current = adjacencies[index];
  96100. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96101. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96102. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96103. }
  96104. // Merge into a single mesh
  96105. var engine = this._source.getScene().getEngine();
  96106. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96107. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96108. this._ib = engine.createIndexBuffer(this._linesIndices);
  96109. this._indicesCount = this._linesIndices.length;
  96110. };
  96111. EdgesRenderer.prototype.render = function () {
  96112. var scene = this._source.getScene();
  96113. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96114. return;
  96115. }
  96116. var engine = scene.getEngine();
  96117. this._lineShader._preBind();
  96118. // VBOs
  96119. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96120. scene.resetCachedMaterial();
  96121. this._lineShader.setColor4("color", this._source.edgesColor);
  96122. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96123. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96124. }
  96125. else {
  96126. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96127. }
  96128. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96129. this._lineShader.bind(this._source.getWorldMatrix());
  96130. // Draw order
  96131. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96132. this._lineShader.unbind();
  96133. engine.setDepthWrite(true);
  96134. };
  96135. return EdgesRenderer;
  96136. }());
  96137. BABYLON.EdgesRenderer = EdgesRenderer;
  96138. })(BABYLON || (BABYLON = {}));
  96139. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96140. var BABYLON;
  96141. (function (BABYLON) {
  96142. // Adds the parser to the scene parsers.
  96143. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96144. if (parsedData.effectLayers) {
  96145. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96146. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96147. container.effectLayers.push(effectLayer);
  96148. }
  96149. }
  96150. });
  96151. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96152. var index = this.effectLayers.indexOf(toRemove);
  96153. if (index !== -1) {
  96154. this.effectLayers.splice(index, 1);
  96155. }
  96156. return index;
  96157. };
  96158. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96159. this.effectLayers.push(newEffectLayer);
  96160. };
  96161. /**
  96162. * Defines the layer scene component responsible to manage any effect layers
  96163. * in a given scene.
  96164. */
  96165. var EffectLayerSceneComponent = /** @class */ (function () {
  96166. /**
  96167. * Creates a new instance of the component for the given scene
  96168. * @param scene Defines the scene to register the component in
  96169. */
  96170. function EffectLayerSceneComponent(scene) {
  96171. /**
  96172. * The component name helpfull to identify the component in the list of scene components.
  96173. */
  96174. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96175. this._renderEffects = false;
  96176. this._needStencil = false;
  96177. this._previousStencilState = false;
  96178. this.scene = scene;
  96179. this._engine = scene.getEngine();
  96180. this._effectLayers = scene.effectLayers = new Array();
  96181. }
  96182. /**
  96183. * Registers the component in a given scene
  96184. */
  96185. EffectLayerSceneComponent.prototype.register = function () {
  96186. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96187. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96188. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96189. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96190. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96191. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96192. };
  96193. /**
  96194. * Rebuilds the elements related to this component in case of
  96195. * context lost for instance.
  96196. */
  96197. EffectLayerSceneComponent.prototype.rebuild = function () {
  96198. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96199. var effectLayer = _a[_i];
  96200. effectLayer._rebuild();
  96201. }
  96202. };
  96203. /**
  96204. * Serializes the component data to the specified json object
  96205. * @param serializationObject The object to serialize to
  96206. */
  96207. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96208. // Effect layers
  96209. serializationObject.effectLayers = [];
  96210. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96211. var effectLayer = _a[_i];
  96212. if (effectLayer.serialize) {
  96213. serializationObject.effectLayers.push(effectLayer.serialize());
  96214. }
  96215. }
  96216. };
  96217. /**
  96218. * Adds all the element from the container to the scene
  96219. * @param container the container holding the elements
  96220. */
  96221. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96222. var _this = this;
  96223. if (!container.effectLayers) {
  96224. return;
  96225. }
  96226. container.effectLayers.forEach(function (o) {
  96227. _this.scene.addEffectLayer(o);
  96228. });
  96229. };
  96230. /**
  96231. * Removes all the elements in the container from the scene
  96232. * @param container contains the elements to remove
  96233. */
  96234. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96235. var _this = this;
  96236. if (!container.effectLayers) {
  96237. return;
  96238. }
  96239. container.effectLayers.forEach(function (o) {
  96240. _this.scene.removeEffectLayer(o);
  96241. });
  96242. };
  96243. /**
  96244. * Disposes the component and the associated ressources.
  96245. */
  96246. EffectLayerSceneComponent.prototype.dispose = function () {
  96247. while (this._effectLayers.length) {
  96248. this._effectLayers[0].dispose();
  96249. }
  96250. };
  96251. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96252. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96253. var layer = _a[_i];
  96254. if (!layer.hasMesh(mesh)) {
  96255. continue;
  96256. }
  96257. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  96258. var subMesh = _c[_b];
  96259. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96260. return false;
  96261. }
  96262. }
  96263. }
  96264. return true;
  96265. };
  96266. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96267. this._renderEffects = false;
  96268. this._needStencil = false;
  96269. if (this._effectLayers && this._effectLayers.length > 0) {
  96270. this._previousStencilState = this._engine.getStencilBuffer();
  96271. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96272. var effectLayer = _a[_i];
  96273. if (effectLayer.shouldRender() &&
  96274. (!effectLayer.camera ||
  96275. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96276. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96277. this._renderEffects = true;
  96278. this._needStencil = this._needStencil || effectLayer.needStencil();
  96279. var renderTarget = effectLayer._mainTexture;
  96280. if (renderTarget._shouldRender()) {
  96281. this.scene.incrementRenderId();
  96282. renderTarget.render(false, false);
  96283. }
  96284. }
  96285. }
  96286. this.scene.incrementRenderId();
  96287. }
  96288. };
  96289. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96290. // Activate effect Layer stencil
  96291. if (this._needStencil) {
  96292. this._engine.setStencilBuffer(true);
  96293. }
  96294. };
  96295. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96296. // Restore effect Layer stencil
  96297. if (this._needStencil) {
  96298. this._engine.setStencilBuffer(this._previousStencilState);
  96299. }
  96300. };
  96301. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96302. if (this._renderEffects) {
  96303. this._engine.setDepthBuffer(false);
  96304. for (var i = 0; i < this._effectLayers.length; i++) {
  96305. var effectLayer = this._effectLayers[i];
  96306. if (effectLayer.renderingGroupId === renderingGroupId) {
  96307. if (effectLayer.shouldRender()) {
  96308. effectLayer.render();
  96309. }
  96310. }
  96311. }
  96312. this._engine.setDepthBuffer(true);
  96313. }
  96314. };
  96315. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96316. if (this._renderEffects) {
  96317. this._draw(-1);
  96318. }
  96319. };
  96320. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96321. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96322. this._draw(index);
  96323. }
  96324. };
  96325. return EffectLayerSceneComponent;
  96326. }());
  96327. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96328. })(BABYLON || (BABYLON = {}));
  96329. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96330. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96331. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96332. s = arguments[i];
  96333. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96334. t[p] = s[p];
  96335. }
  96336. return t;
  96337. };
  96338. var BABYLON;
  96339. (function (BABYLON) {
  96340. /**
  96341. * The effect layer Helps adding post process effect blended with the main pass.
  96342. *
  96343. * This can be for instance use to generate glow or higlight effects on the scene.
  96344. *
  96345. * The effect layer class can not be used directly and is intented to inherited from to be
  96346. * customized per effects.
  96347. */
  96348. var EffectLayer = /** @class */ (function () {
  96349. /**
  96350. * Instantiates a new effect Layer and references it in the scene.
  96351. * @param name The name of the layer
  96352. * @param scene The scene to use the layer in
  96353. */
  96354. function EffectLayer(
  96355. /** The Friendly of the effect in the scene */
  96356. name, scene) {
  96357. this._vertexBuffers = {};
  96358. this._maxSize = 0;
  96359. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96360. this._shouldRender = true;
  96361. this._postProcesses = [];
  96362. this._textures = [];
  96363. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96364. /**
  96365. * The clear color of the texture used to generate the glow map.
  96366. */
  96367. this.neutralColor = new BABYLON.Color4();
  96368. /**
  96369. * Specifies wether the highlight layer is enabled or not.
  96370. */
  96371. this.isEnabled = true;
  96372. /**
  96373. * An event triggered when the effect layer has been disposed.
  96374. */
  96375. this.onDisposeObservable = new BABYLON.Observable();
  96376. /**
  96377. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96378. */
  96379. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96380. /**
  96381. * An event triggered when the generated texture is being merged in the scene.
  96382. */
  96383. this.onBeforeComposeObservable = new BABYLON.Observable();
  96384. /**
  96385. * An event triggered when the generated texture has been merged in the scene.
  96386. */
  96387. this.onAfterComposeObservable = new BABYLON.Observable();
  96388. /**
  96389. * An event triggered when the efffect layer changes its size.
  96390. */
  96391. this.onSizeChangedObservable = new BABYLON.Observable();
  96392. this.name = name;
  96393. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96394. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96395. if (!component) {
  96396. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96397. this._scene._addComponent(component);
  96398. }
  96399. this._engine = this._scene.getEngine();
  96400. this._maxSize = this._engine.getCaps().maxTextureSize;
  96401. this._scene.effectLayers.push(this);
  96402. // Generate Buffers
  96403. this._generateIndexBuffer();
  96404. this._genrateVertexBuffer();
  96405. }
  96406. Object.defineProperty(EffectLayer.prototype, "camera", {
  96407. /**
  96408. * Gets the camera attached to the layer.
  96409. */
  96410. get: function () {
  96411. return this._effectLayerOptions.camera;
  96412. },
  96413. enumerable: true,
  96414. configurable: true
  96415. });
  96416. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96417. /**
  96418. * Gets the rendering group id the layer should render in.
  96419. */
  96420. get: function () {
  96421. return this._effectLayerOptions.renderingGroupId;
  96422. },
  96423. enumerable: true,
  96424. configurable: true
  96425. });
  96426. /**
  96427. * Initializes the effect layer with the required options.
  96428. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96429. */
  96430. EffectLayer.prototype._init = function (options) {
  96431. // Adapt options
  96432. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96433. this._setMainTextureSize();
  96434. this._createMainTexture();
  96435. this._createTextureAndPostProcesses();
  96436. this._mergeEffect = this._createMergeEffect();
  96437. };
  96438. /**
  96439. * Generates the index buffer of the full screen quad blending to the main canvas.
  96440. */
  96441. EffectLayer.prototype._generateIndexBuffer = function () {
  96442. // Indices
  96443. var indices = [];
  96444. indices.push(0);
  96445. indices.push(1);
  96446. indices.push(2);
  96447. indices.push(0);
  96448. indices.push(2);
  96449. indices.push(3);
  96450. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96451. };
  96452. /**
  96453. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96454. */
  96455. EffectLayer.prototype._genrateVertexBuffer = function () {
  96456. // VBO
  96457. var vertices = [];
  96458. vertices.push(1, 1);
  96459. vertices.push(-1, 1);
  96460. vertices.push(-1, -1);
  96461. vertices.push(1, -1);
  96462. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96463. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96464. };
  96465. /**
  96466. * Sets the main texture desired size which is the closest power of two
  96467. * of the engine canvas size.
  96468. */
  96469. EffectLayer.prototype._setMainTextureSize = function () {
  96470. if (this._effectLayerOptions.mainTextureFixedSize) {
  96471. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96472. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96473. }
  96474. else {
  96475. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96476. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96477. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96478. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96479. }
  96480. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96481. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96482. };
  96483. /**
  96484. * Creates the main texture for the effect layer.
  96485. */
  96486. EffectLayer.prototype._createMainTexture = function () {
  96487. var _this = this;
  96488. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96489. width: this._mainTextureDesiredSize.width,
  96490. height: this._mainTextureDesiredSize.height
  96491. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96492. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96493. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96494. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96495. this._mainTexture.anisotropicFilteringLevel = 1;
  96496. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96497. this._mainTexture.renderParticles = false;
  96498. this._mainTexture.renderList = null;
  96499. this._mainTexture.ignoreCameraViewport = true;
  96500. // Custom render function
  96501. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96502. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96503. var index;
  96504. var engine = _this._scene.getEngine();
  96505. if (depthOnlySubMeshes.length) {
  96506. engine.setColorWrite(false);
  96507. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96508. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96509. }
  96510. engine.setColorWrite(true);
  96511. }
  96512. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96513. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96514. }
  96515. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96516. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96517. }
  96518. for (index = 0; index < transparentSubMeshes.length; index++) {
  96519. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96520. }
  96521. };
  96522. this._mainTexture.onClearObservable.add(function (engine) {
  96523. engine.clear(_this.neutralColor, true, true, true);
  96524. });
  96525. };
  96526. /**
  96527. * Checks for the readiness of the element composing the layer.
  96528. * @param subMesh the mesh to check for
  96529. * @param useInstances specify wether or not to use instances to render the mesh
  96530. * @param emissiveTexture the associated emissive texture used to generate the glow
  96531. * @return true if ready otherwise, false
  96532. */
  96533. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96534. var material = subMesh.getMaterial();
  96535. if (!material) {
  96536. return false;
  96537. }
  96538. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96539. return false;
  96540. }
  96541. var defines = [];
  96542. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96543. var mesh = subMesh.getMesh();
  96544. var uv1 = false;
  96545. var uv2 = false;
  96546. // Alpha test
  96547. if (material && material.needAlphaTesting()) {
  96548. var alphaTexture = material.getAlphaTestTexture();
  96549. if (alphaTexture) {
  96550. defines.push("#define ALPHATEST");
  96551. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96552. alphaTexture.coordinatesIndex === 1) {
  96553. defines.push("#define DIFFUSEUV2");
  96554. uv2 = true;
  96555. }
  96556. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96557. defines.push("#define DIFFUSEUV1");
  96558. uv1 = true;
  96559. }
  96560. }
  96561. }
  96562. // Emissive
  96563. if (emissiveTexture) {
  96564. defines.push("#define EMISSIVE");
  96565. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96566. emissiveTexture.coordinatesIndex === 1) {
  96567. defines.push("#define EMISSIVEUV2");
  96568. uv2 = true;
  96569. }
  96570. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96571. defines.push("#define EMISSIVEUV1");
  96572. uv1 = true;
  96573. }
  96574. }
  96575. if (uv1) {
  96576. attribs.push(BABYLON.VertexBuffer.UVKind);
  96577. defines.push("#define UV1");
  96578. }
  96579. if (uv2) {
  96580. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96581. defines.push("#define UV2");
  96582. }
  96583. // Bones
  96584. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96585. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96586. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96587. if (mesh.numBoneInfluencers > 4) {
  96588. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96589. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96590. }
  96591. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96592. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96593. }
  96594. else {
  96595. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96596. }
  96597. // Morph targets
  96598. var manager = mesh.morphTargetManager;
  96599. var morphInfluencers = 0;
  96600. if (manager) {
  96601. if (manager.numInfluencers > 0) {
  96602. defines.push("#define MORPHTARGETS");
  96603. morphInfluencers = manager.numInfluencers;
  96604. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96605. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96606. }
  96607. }
  96608. // Instances
  96609. if (useInstances) {
  96610. defines.push("#define INSTANCES");
  96611. attribs.push("world0");
  96612. attribs.push("world1");
  96613. attribs.push("world2");
  96614. attribs.push("world3");
  96615. }
  96616. // Get correct effect
  96617. var join = defines.join("\n");
  96618. if (this._cachedDefines !== join) {
  96619. this._cachedDefines = join;
  96620. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96621. }
  96622. return this._effectLayerMapGenerationEffect.isReady();
  96623. };
  96624. /**
  96625. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96626. */
  96627. EffectLayer.prototype.render = function () {
  96628. var currentEffect = this._mergeEffect;
  96629. // Check
  96630. if (!currentEffect.isReady())
  96631. return;
  96632. for (var i = 0; i < this._postProcesses.length; i++) {
  96633. if (!this._postProcesses[i].isReady()) {
  96634. return;
  96635. }
  96636. }
  96637. var engine = this._scene.getEngine();
  96638. this.onBeforeComposeObservable.notifyObservers(this);
  96639. // Render
  96640. engine.enableEffect(currentEffect);
  96641. engine.setState(false);
  96642. // VBOs
  96643. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96644. // Cache
  96645. var previousAlphaMode = engine.getAlphaMode();
  96646. // Go Blend.
  96647. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96648. // Blends the map on the main canvas.
  96649. this._internalRender(currentEffect);
  96650. // Restore Alpha
  96651. engine.setAlphaMode(previousAlphaMode);
  96652. this.onAfterComposeObservable.notifyObservers(this);
  96653. // Handle size changes.
  96654. var size = this._mainTexture.getSize();
  96655. this._setMainTextureSize();
  96656. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96657. // Recreate RTT and post processes on size change.
  96658. this.onSizeChangedObservable.notifyObservers(this);
  96659. this._disposeTextureAndPostProcesses();
  96660. this._createMainTexture();
  96661. this._createTextureAndPostProcesses();
  96662. }
  96663. };
  96664. /**
  96665. * Determine if a given mesh will be used in the current effect.
  96666. * @param mesh mesh to test
  96667. * @returns true if the mesh will be used
  96668. */
  96669. EffectLayer.prototype.hasMesh = function (mesh) {
  96670. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  96671. return true;
  96672. }
  96673. return false;
  96674. };
  96675. /**
  96676. * Returns true if the layer contains information to display, otherwise false.
  96677. * @returns true if the glow layer should be rendered
  96678. */
  96679. EffectLayer.prototype.shouldRender = function () {
  96680. return this.isEnabled && this._shouldRender;
  96681. };
  96682. /**
  96683. * Returns true if the mesh should render, otherwise false.
  96684. * @param mesh The mesh to render
  96685. * @returns true if it should render otherwise false
  96686. */
  96687. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96688. return true;
  96689. };
  96690. /**
  96691. * Returns true if the mesh should render, otherwise false.
  96692. * @param mesh The mesh to render
  96693. * @returns true if it should render otherwise false
  96694. */
  96695. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96696. return true;
  96697. };
  96698. /**
  96699. * Renders the submesh passed in parameter to the generation map.
  96700. */
  96701. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96702. var _this = this;
  96703. if (!this.shouldRender()) {
  96704. return;
  96705. }
  96706. var material = subMesh.getMaterial();
  96707. var mesh = subMesh.getRenderingMesh();
  96708. var scene = this._scene;
  96709. var engine = scene.getEngine();
  96710. if (!material) {
  96711. return;
  96712. }
  96713. // Do not block in blend mode.
  96714. if (material.needAlphaBlendingForMesh(mesh)) {
  96715. return;
  96716. }
  96717. // Culling
  96718. engine.setState(material.backFaceCulling);
  96719. // Managing instances
  96720. var batch = mesh._getInstancesRenderList(subMesh._id);
  96721. if (batch.mustReturn) {
  96722. return;
  96723. }
  96724. // Early Exit per mesh
  96725. if (!this._shouldRenderMesh(mesh)) {
  96726. return;
  96727. }
  96728. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96729. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96730. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96731. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96732. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96733. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96734. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96735. // Alpha test
  96736. if (material && material.needAlphaTesting()) {
  96737. var alphaTexture = material.getAlphaTestTexture();
  96738. if (alphaTexture) {
  96739. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96740. var textureMatrix = alphaTexture.getTextureMatrix();
  96741. if (textureMatrix) {
  96742. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96743. }
  96744. }
  96745. }
  96746. // Glow emissive only
  96747. if (this._emissiveTextureAndColor.texture) {
  96748. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96749. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96750. }
  96751. // Bones
  96752. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96753. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96754. }
  96755. // Morph targets
  96756. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96757. // Draw
  96758. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96759. }
  96760. else {
  96761. // Need to reset refresh rate of the main map
  96762. this._mainTexture.resetRefreshCounter();
  96763. }
  96764. };
  96765. /**
  96766. * Rebuild the required buffers.
  96767. * @hidden Internal use only.
  96768. */
  96769. EffectLayer.prototype._rebuild = function () {
  96770. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96771. if (vb) {
  96772. vb._rebuild();
  96773. }
  96774. this._generateIndexBuffer();
  96775. };
  96776. /**
  96777. * Dispose only the render target textures and post process.
  96778. */
  96779. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96780. this._mainTexture.dispose();
  96781. for (var i = 0; i < this._postProcesses.length; i++) {
  96782. if (this._postProcesses[i]) {
  96783. this._postProcesses[i].dispose();
  96784. }
  96785. }
  96786. this._postProcesses = [];
  96787. for (var i = 0; i < this._textures.length; i++) {
  96788. if (this._textures[i]) {
  96789. this._textures[i].dispose();
  96790. }
  96791. }
  96792. this._textures = [];
  96793. };
  96794. /**
  96795. * Dispose the highlight layer and free resources.
  96796. */
  96797. EffectLayer.prototype.dispose = function () {
  96798. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96799. if (vertexBuffer) {
  96800. vertexBuffer.dispose();
  96801. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96802. }
  96803. if (this._indexBuffer) {
  96804. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96805. this._indexBuffer = null;
  96806. }
  96807. // Clean textures and post processes
  96808. this._disposeTextureAndPostProcesses();
  96809. // Remove from scene
  96810. var index = this._scene.effectLayers.indexOf(this, 0);
  96811. if (index > -1) {
  96812. this._scene.effectLayers.splice(index, 1);
  96813. }
  96814. // Callback
  96815. this.onDisposeObservable.notifyObservers(this);
  96816. this.onDisposeObservable.clear();
  96817. this.onBeforeRenderMainTextureObservable.clear();
  96818. this.onBeforeComposeObservable.clear();
  96819. this.onAfterComposeObservable.clear();
  96820. this.onSizeChangedObservable.clear();
  96821. };
  96822. /**
  96823. * Gets the class name of the effect layer
  96824. * @returns the string with the class name of the effect layer
  96825. */
  96826. EffectLayer.prototype.getClassName = function () {
  96827. return "EffectLayer";
  96828. };
  96829. /**
  96830. * Creates an effect layer from parsed effect layer data
  96831. * @param parsedEffectLayer defines effect layer data
  96832. * @param scene defines the current scene
  96833. * @param rootUrl defines the root URL containing the effect layer information
  96834. * @returns a parsed effect Layer
  96835. */
  96836. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96837. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96838. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96839. };
  96840. __decorate([
  96841. BABYLON.serialize()
  96842. ], EffectLayer.prototype, "name", void 0);
  96843. __decorate([
  96844. BABYLON.serializeAsColor4()
  96845. ], EffectLayer.prototype, "neutralColor", void 0);
  96846. __decorate([
  96847. BABYLON.serialize()
  96848. ], EffectLayer.prototype, "isEnabled", void 0);
  96849. __decorate([
  96850. BABYLON.serializeAsCameraReference()
  96851. ], EffectLayer.prototype, "camera", null);
  96852. __decorate([
  96853. BABYLON.serialize()
  96854. ], EffectLayer.prototype, "renderingGroupId", null);
  96855. return EffectLayer;
  96856. }());
  96857. BABYLON.EffectLayer = EffectLayer;
  96858. })(BABYLON || (BABYLON = {}));
  96859. //# sourceMappingURL=babylon.effectLayer.js.map
  96860. var BABYLON;
  96861. (function (BABYLON) {
  96862. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  96863. for (var index = 0; index < this.effectLayers.length; index++) {
  96864. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  96865. return this.effectLayers[index];
  96866. }
  96867. }
  96868. return null;
  96869. };
  96870. /**
  96871. * Special Glow Blur post process only blurring the alpha channel
  96872. * It enforces keeping the most luminous color in the color channel.
  96873. */
  96874. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96875. __extends(GlowBlurPostProcess, _super);
  96876. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96878. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96879. _this.direction = direction;
  96880. _this.kernel = kernel;
  96881. _this.onApplyObservable.add(function (effect) {
  96882. effect.setFloat2("screenSize", _this.width, _this.height);
  96883. effect.setVector2("direction", _this.direction);
  96884. effect.setFloat("blurWidth", _this.kernel);
  96885. });
  96886. return _this;
  96887. }
  96888. return GlowBlurPostProcess;
  96889. }(BABYLON.PostProcess));
  96890. /**
  96891. * The highlight layer Helps adding a glow effect around a mesh.
  96892. *
  96893. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96894. * glowy meshes to your scene.
  96895. *
  96896. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96897. */
  96898. var HighlightLayer = /** @class */ (function (_super) {
  96899. __extends(HighlightLayer, _super);
  96900. /**
  96901. * Instantiates a new highlight Layer and references it to the scene..
  96902. * @param name The name of the layer
  96903. * @param scene The scene to use the layer in
  96904. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96905. */
  96906. function HighlightLayer(name, scene, options) {
  96907. var _this = _super.call(this, name, scene) || this;
  96908. _this.name = name;
  96909. /**
  96910. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96911. */
  96912. _this.innerGlow = true;
  96913. /**
  96914. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96915. */
  96916. _this.outerGlow = true;
  96917. /**
  96918. * An event triggered when the highlight layer is being blurred.
  96919. */
  96920. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96921. /**
  96922. * An event triggered when the highlight layer has been blurred.
  96923. */
  96924. _this.onAfterBlurObservable = new BABYLON.Observable();
  96925. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96926. _this._meshes = {};
  96927. _this._excludedMeshes = {};
  96928. _this.neutralColor = HighlightLayer.NeutralColor;
  96929. // Warn on stencil
  96930. if (!_this._engine.isStencilEnable) {
  96931. 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 }");
  96932. }
  96933. // Adapt options
  96934. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96935. // Initialize the layer
  96936. _this._init({
  96937. alphaBlendingMode: _this._options.alphaBlendingMode,
  96938. camera: _this._options.camera,
  96939. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96940. mainTextureRatio: _this._options.mainTextureRatio,
  96941. renderingGroupId: _this._options.renderingGroupId
  96942. });
  96943. // Do not render as long as no meshes have been added
  96944. _this._shouldRender = false;
  96945. return _this;
  96946. }
  96947. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96948. /**
  96949. * Gets the horizontal size of the blur.
  96950. */
  96951. get: function () {
  96952. return this._horizontalBlurPostprocess.kernel;
  96953. },
  96954. /**
  96955. * Specifies the horizontal size of the blur.
  96956. */
  96957. set: function (value) {
  96958. this._horizontalBlurPostprocess.kernel = value;
  96959. },
  96960. enumerable: true,
  96961. configurable: true
  96962. });
  96963. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96964. /**
  96965. * Gets the vertical size of the blur.
  96966. */
  96967. get: function () {
  96968. return this._verticalBlurPostprocess.kernel;
  96969. },
  96970. /**
  96971. * Specifies the vertical size of the blur.
  96972. */
  96973. set: function (value) {
  96974. this._verticalBlurPostprocess.kernel = value;
  96975. },
  96976. enumerable: true,
  96977. configurable: true
  96978. });
  96979. /**
  96980. * Get the effect name of the layer.
  96981. * @return The effect name
  96982. */
  96983. HighlightLayer.prototype.getEffectName = function () {
  96984. return HighlightLayer.EffectName;
  96985. };
  96986. /**
  96987. * Create the merge effect. This is the shader use to blit the information back
  96988. * to the main canvas at the end of the scene rendering.
  96989. */
  96990. HighlightLayer.prototype._createMergeEffect = function () {
  96991. // Effect
  96992. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  96993. };
  96994. /**
  96995. * Creates the render target textures and post processes used in the highlight layer.
  96996. */
  96997. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  96998. var _this = this;
  96999. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97000. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97001. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97002. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97003. var textureType = 0;
  97004. if (this._engine.getCaps().textureHalfFloatRender) {
  97005. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97006. }
  97007. else {
  97008. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97009. }
  97010. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97011. width: blurTextureWidth,
  97012. height: blurTextureHeight
  97013. }, this._scene, false, true, textureType);
  97014. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97015. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97016. this._blurTexture.anisotropicFilteringLevel = 16;
  97017. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97018. this._blurTexture.renderParticles = false;
  97019. this._blurTexture.ignoreCameraViewport = true;
  97020. this._textures = [this._blurTexture];
  97021. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97022. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97023. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97024. effect.setTexture("textureSampler", _this._mainTexture);
  97025. });
  97026. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97027. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97028. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97029. });
  97030. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97031. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97032. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97033. });
  97034. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97035. }
  97036. else {
  97037. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97038. width: blurTextureWidth,
  97039. height: blurTextureHeight
  97040. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97041. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97042. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97043. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97044. effect.setTexture("textureSampler", _this._mainTexture);
  97045. });
  97046. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97047. width: blurTextureWidth,
  97048. height: blurTextureHeight
  97049. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97050. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97051. }
  97052. this._mainTexture.onAfterUnbindObservable.add(function () {
  97053. _this.onBeforeBlurObservable.notifyObservers(_this);
  97054. var internalTexture = _this._blurTexture.getInternalTexture();
  97055. if (internalTexture) {
  97056. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97057. }
  97058. _this.onAfterBlurObservable.notifyObservers(_this);
  97059. });
  97060. // Prevent autoClear.
  97061. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97062. };
  97063. /**
  97064. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97065. */
  97066. HighlightLayer.prototype.needStencil = function () {
  97067. return true;
  97068. };
  97069. /**
  97070. * Checks for the readiness of the element composing the layer.
  97071. * @param subMesh the mesh to check for
  97072. * @param useInstances specify wether or not to use instances to render the mesh
  97073. * @param emissiveTexture the associated emissive texture used to generate the glow
  97074. * @return true if ready otherwise, false
  97075. */
  97076. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97077. var material = subMesh.getMaterial();
  97078. var mesh = subMesh.getRenderingMesh();
  97079. if (!material || !mesh || !this._meshes) {
  97080. return false;
  97081. }
  97082. var emissiveTexture = null;
  97083. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97084. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97085. emissiveTexture = material.emissiveTexture;
  97086. }
  97087. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97088. };
  97089. /**
  97090. * Implementation specific of rendering the generating effect on the main canvas.
  97091. * @param effect The effect used to render through
  97092. */
  97093. HighlightLayer.prototype._internalRender = function (effect) {
  97094. // Texture
  97095. effect.setTexture("textureSampler", this._blurTexture);
  97096. // Cache
  97097. var engine = this._engine;
  97098. var previousStencilBuffer = engine.getStencilBuffer();
  97099. var previousStencilFunction = engine.getStencilFunction();
  97100. var previousStencilMask = engine.getStencilMask();
  97101. var previousStencilOperationPass = engine.getStencilOperationPass();
  97102. var previousStencilOperationFail = engine.getStencilOperationFail();
  97103. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97104. var previousStencilReference = engine.getStencilFunctionReference();
  97105. // Stencil operations
  97106. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97107. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97108. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97109. // Draw order
  97110. engine.setStencilMask(0x00);
  97111. engine.setStencilBuffer(true);
  97112. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97113. // 2 passes inner outer
  97114. if (this.outerGlow) {
  97115. effect.setFloat("offset", 0);
  97116. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97117. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97118. }
  97119. if (this.innerGlow) {
  97120. effect.setFloat("offset", 1);
  97121. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97122. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97123. }
  97124. // Restore Cache
  97125. engine.setStencilFunction(previousStencilFunction);
  97126. engine.setStencilMask(previousStencilMask);
  97127. engine.setStencilBuffer(previousStencilBuffer);
  97128. engine.setStencilOperationPass(previousStencilOperationPass);
  97129. engine.setStencilOperationFail(previousStencilOperationFail);
  97130. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97131. engine.setStencilFunctionReference(previousStencilReference);
  97132. };
  97133. /**
  97134. * Returns true if the layer contains information to display, otherwise false.
  97135. */
  97136. HighlightLayer.prototype.shouldRender = function () {
  97137. if (_super.prototype.shouldRender.call(this)) {
  97138. return this._meshes ? true : false;
  97139. }
  97140. return false;
  97141. };
  97142. /**
  97143. * Returns true if the mesh should render, otherwise false.
  97144. * @param mesh The mesh to render
  97145. * @returns true if it should render otherwise false
  97146. */
  97147. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97148. // Excluded Mesh
  97149. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97150. return false;
  97151. }
  97152. ;
  97153. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97154. return false;
  97155. }
  97156. return true;
  97157. };
  97158. /**
  97159. * Sets the required values for both the emissive texture and and the main color.
  97160. */
  97161. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97162. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97163. if (highlightLayerMesh) {
  97164. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97165. }
  97166. else {
  97167. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97168. }
  97169. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97170. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97171. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97172. }
  97173. else {
  97174. this._emissiveTextureAndColor.texture = null;
  97175. }
  97176. };
  97177. /**
  97178. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97179. * @param mesh The mesh to exclude from the highlight layer
  97180. */
  97181. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97182. if (!this._excludedMeshes) {
  97183. return;
  97184. }
  97185. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97186. if (!meshExcluded) {
  97187. this._excludedMeshes[mesh.uniqueId] = {
  97188. mesh: mesh,
  97189. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97190. mesh.getEngine().setStencilBuffer(false);
  97191. }),
  97192. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97193. mesh.getEngine().setStencilBuffer(true);
  97194. }),
  97195. };
  97196. }
  97197. };
  97198. /**
  97199. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97200. * @param mesh The mesh to highlight
  97201. */
  97202. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97203. if (!this._excludedMeshes) {
  97204. return;
  97205. }
  97206. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97207. if (meshExcluded) {
  97208. if (meshExcluded.beforeRender) {
  97209. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97210. }
  97211. if (meshExcluded.afterRender) {
  97212. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97213. }
  97214. }
  97215. this._excludedMeshes[mesh.uniqueId] = null;
  97216. };
  97217. /**
  97218. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97219. * @param mesh mesh to test
  97220. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97221. */
  97222. HighlightLayer.prototype.hasMesh = function (mesh) {
  97223. if (!this._meshes) {
  97224. return false;
  97225. }
  97226. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97227. return false;
  97228. }
  97229. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97230. };
  97231. /**
  97232. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97233. * @param mesh The mesh to highlight
  97234. * @param color The color of the highlight
  97235. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97236. */
  97237. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97238. var _this = this;
  97239. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97240. if (!this._meshes) {
  97241. return;
  97242. }
  97243. var meshHighlight = this._meshes[mesh.uniqueId];
  97244. if (meshHighlight) {
  97245. meshHighlight.color = color;
  97246. }
  97247. else {
  97248. this._meshes[mesh.uniqueId] = {
  97249. mesh: mesh,
  97250. color: color,
  97251. // Lambda required for capture due to Observable this context
  97252. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97253. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97254. _this._defaultStencilReference(mesh);
  97255. }
  97256. else {
  97257. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97258. }
  97259. }),
  97260. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97261. glowEmissiveOnly: glowEmissiveOnly
  97262. };
  97263. mesh.onDisposeObservable.add(function () {
  97264. _this._disposeMesh(mesh);
  97265. });
  97266. }
  97267. this._shouldRender = true;
  97268. };
  97269. /**
  97270. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97271. * @param mesh The mesh to highlight
  97272. */
  97273. HighlightLayer.prototype.removeMesh = function (mesh) {
  97274. if (!this._meshes) {
  97275. return;
  97276. }
  97277. var meshHighlight = this._meshes[mesh.uniqueId];
  97278. if (meshHighlight) {
  97279. if (meshHighlight.observerHighlight) {
  97280. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97281. }
  97282. if (meshHighlight.observerDefault) {
  97283. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97284. }
  97285. delete this._meshes[mesh.uniqueId];
  97286. }
  97287. this._shouldRender = false;
  97288. for (var meshHighlightToCheck in this._meshes) {
  97289. if (this._meshes[meshHighlightToCheck]) {
  97290. this._shouldRender = true;
  97291. break;
  97292. }
  97293. }
  97294. };
  97295. /**
  97296. * Force the stencil to the normal expected value for none glowing parts
  97297. */
  97298. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97299. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97300. };
  97301. /**
  97302. * Free any resources and references associated to a mesh.
  97303. * Internal use
  97304. * @param mesh The mesh to free.
  97305. */
  97306. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97307. this.removeMesh(mesh);
  97308. this.removeExcludedMesh(mesh);
  97309. };
  97310. /**
  97311. * Dispose the highlight layer and free resources.
  97312. */
  97313. HighlightLayer.prototype.dispose = function () {
  97314. if (this._meshes) {
  97315. // Clean mesh references
  97316. for (var id in this._meshes) {
  97317. var meshHighlight = this._meshes[id];
  97318. if (meshHighlight && meshHighlight.mesh) {
  97319. if (meshHighlight.observerHighlight) {
  97320. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97321. }
  97322. if (meshHighlight.observerDefault) {
  97323. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97324. }
  97325. }
  97326. }
  97327. this._meshes = null;
  97328. }
  97329. if (this._excludedMeshes) {
  97330. for (var id in this._excludedMeshes) {
  97331. var meshHighlight = this._excludedMeshes[id];
  97332. if (meshHighlight) {
  97333. if (meshHighlight.beforeRender) {
  97334. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97335. }
  97336. if (meshHighlight.afterRender) {
  97337. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97338. }
  97339. }
  97340. }
  97341. this._excludedMeshes = null;
  97342. }
  97343. _super.prototype.dispose.call(this);
  97344. };
  97345. /**
  97346. * Gets the class name of the effect layer
  97347. * @returns the string with the class name of the effect layer
  97348. */
  97349. HighlightLayer.prototype.getClassName = function () {
  97350. return "HighlightLayer";
  97351. };
  97352. /**
  97353. * Serializes this Highlight layer
  97354. * @returns a serialized Highlight layer object
  97355. */
  97356. HighlightLayer.prototype.serialize = function () {
  97357. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97358. serializationObject.customType = "BABYLON.HighlightLayer";
  97359. // Highlighted meshes
  97360. serializationObject.meshes = [];
  97361. if (this._meshes) {
  97362. for (var m in this._meshes) {
  97363. var mesh = this._meshes[m];
  97364. if (mesh) {
  97365. serializationObject.meshes.push({
  97366. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97367. color: mesh.color.asArray(),
  97368. meshId: mesh.mesh.id
  97369. });
  97370. }
  97371. }
  97372. }
  97373. // Excluded meshes
  97374. serializationObject.excludedMeshes = [];
  97375. if (this._excludedMeshes) {
  97376. for (var e in this._excludedMeshes) {
  97377. var excludedMesh = this._excludedMeshes[e];
  97378. if (excludedMesh) {
  97379. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97380. }
  97381. }
  97382. }
  97383. return serializationObject;
  97384. };
  97385. /**
  97386. * Creates a Highlight layer from parsed Highlight layer data
  97387. * @param parsedHightlightLayer defines the Highlight layer data
  97388. * @param scene defines the current scene
  97389. * @param rootUrl defines the root URL containing the Highlight layer information
  97390. * @returns a parsed Highlight layer
  97391. */
  97392. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97393. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97394. var index;
  97395. // Excluded meshes
  97396. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97397. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97398. if (mesh) {
  97399. hl.addExcludedMesh(mesh);
  97400. }
  97401. }
  97402. // Included meshes
  97403. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97404. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97405. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97406. if (mesh) {
  97407. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97408. }
  97409. }
  97410. return hl;
  97411. };
  97412. /**
  97413. * Effect Name of the highlight layer.
  97414. */
  97415. HighlightLayer.EffectName = "HighlightLayer";
  97416. /**
  97417. * The neutral color used during the preparation of the glow effect.
  97418. * This is black by default as the blend operation is a blend operation.
  97419. */
  97420. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97421. /**
  97422. * Stencil value used for glowing meshes.
  97423. */
  97424. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97425. /**
  97426. * Stencil value used for the other meshes in the scene.
  97427. */
  97428. HighlightLayer.NormalMeshStencilReference = 0x01;
  97429. __decorate([
  97430. BABYLON.serialize()
  97431. ], HighlightLayer.prototype, "innerGlow", void 0);
  97432. __decorate([
  97433. BABYLON.serialize()
  97434. ], HighlightLayer.prototype, "outerGlow", void 0);
  97435. __decorate([
  97436. BABYLON.serialize()
  97437. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97438. __decorate([
  97439. BABYLON.serialize()
  97440. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97441. __decorate([
  97442. BABYLON.serialize("options")
  97443. ], HighlightLayer.prototype, "_options", void 0);
  97444. return HighlightLayer;
  97445. }(BABYLON.EffectLayer));
  97446. BABYLON.HighlightLayer = HighlightLayer;
  97447. })(BABYLON || (BABYLON = {}));
  97448. //# sourceMappingURL=babylon.highlightLayer.js.map
  97449. var BABYLON;
  97450. (function (BABYLON) {
  97451. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97452. for (var index = 0; index < this.effectLayers.length; index++) {
  97453. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97454. return this.effectLayers[index];
  97455. }
  97456. }
  97457. return null;
  97458. };
  97459. /**
  97460. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97461. *
  97462. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97463. * glowy meshes to your scene.
  97464. *
  97465. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97466. */
  97467. var GlowLayer = /** @class */ (function (_super) {
  97468. __extends(GlowLayer, _super);
  97469. /**
  97470. * Instantiates a new glow Layer and references it to the scene.
  97471. * @param name The name of the layer
  97472. * @param scene The scene to use the layer in
  97473. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97474. */
  97475. function GlowLayer(name, scene, options) {
  97476. var _this = _super.call(this, name, scene) || this;
  97477. _this._intensity = 1.0;
  97478. _this._includedOnlyMeshes = [];
  97479. _this._excludedMeshes = [];
  97480. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97481. // Adapt options
  97482. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97483. // Initialize the layer
  97484. _this._init({
  97485. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97486. camera: _this._options.camera,
  97487. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97488. mainTextureRatio: _this._options.mainTextureRatio,
  97489. renderingGroupId: _this._options.renderingGroupId
  97490. });
  97491. return _this;
  97492. }
  97493. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97494. /**
  97495. * Gets the kernel size of the blur.
  97496. */
  97497. get: function () {
  97498. return this._horizontalBlurPostprocess1.kernel;
  97499. },
  97500. /**
  97501. * Sets the kernel size of the blur.
  97502. */
  97503. set: function (value) {
  97504. this._horizontalBlurPostprocess1.kernel = value;
  97505. this._verticalBlurPostprocess1.kernel = value;
  97506. this._horizontalBlurPostprocess2.kernel = value;
  97507. this._verticalBlurPostprocess2.kernel = value;
  97508. },
  97509. enumerable: true,
  97510. configurable: true
  97511. });
  97512. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97513. /**
  97514. * Gets the glow intensity.
  97515. */
  97516. get: function () {
  97517. return this._intensity;
  97518. },
  97519. /**
  97520. * Sets the glow intensity.
  97521. */
  97522. set: function (value) {
  97523. this._intensity = value;
  97524. },
  97525. enumerable: true,
  97526. configurable: true
  97527. });
  97528. /**
  97529. * Get the effect name of the layer.
  97530. * @return The effect name
  97531. */
  97532. GlowLayer.prototype.getEffectName = function () {
  97533. return GlowLayer.EffectName;
  97534. };
  97535. /**
  97536. * Create the merge effect. This is the shader use to blit the information back
  97537. * to the main canvas at the end of the scene rendering.
  97538. */
  97539. GlowLayer.prototype._createMergeEffect = function () {
  97540. // Effect
  97541. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97542. };
  97543. /**
  97544. * Creates the render target textures and post processes used in the glow layer.
  97545. */
  97546. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97547. var _this = this;
  97548. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97549. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97550. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97551. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97552. var textureType = 0;
  97553. if (this._engine.getCaps().textureHalfFloatRender) {
  97554. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97555. }
  97556. else {
  97557. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97558. }
  97559. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97560. width: blurTextureWidth,
  97561. height: blurTextureHeight
  97562. }, this._scene, false, true, textureType);
  97563. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97564. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97565. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97566. this._blurTexture1.renderParticles = false;
  97567. this._blurTexture1.ignoreCameraViewport = true;
  97568. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97569. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97570. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97571. width: blurTextureWidth2,
  97572. height: blurTextureHeight2
  97573. }, this._scene, false, true, textureType);
  97574. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97575. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97576. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97577. this._blurTexture2.renderParticles = false;
  97578. this._blurTexture2.ignoreCameraViewport = true;
  97579. this._textures = [this._blurTexture1, this._blurTexture2];
  97580. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97581. width: blurTextureWidth,
  97582. height: blurTextureHeight
  97583. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97584. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97585. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97586. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97587. effect.setTexture("textureSampler", _this._mainTexture);
  97588. });
  97589. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97590. width: blurTextureWidth,
  97591. height: blurTextureHeight
  97592. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97593. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97594. width: blurTextureWidth2,
  97595. height: blurTextureHeight2
  97596. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97597. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97598. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97599. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97600. effect.setTexture("textureSampler", _this._blurTexture1);
  97601. });
  97602. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97603. width: blurTextureWidth2,
  97604. height: blurTextureHeight2
  97605. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97606. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97607. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97608. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97609. this._mainTexture.samples = this._options.mainTextureSamples;
  97610. this._mainTexture.onAfterUnbindObservable.add(function () {
  97611. var internalTexture = _this._blurTexture1.getInternalTexture();
  97612. if (internalTexture) {
  97613. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97614. internalTexture = _this._blurTexture2.getInternalTexture();
  97615. if (internalTexture) {
  97616. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97617. }
  97618. }
  97619. });
  97620. // Prevent autoClear.
  97621. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97622. };
  97623. /**
  97624. * Checks for the readiness of the element composing the layer.
  97625. * @param subMesh the mesh to check for
  97626. * @param useInstances specify wether or not to use instances to render the mesh
  97627. * @param emissiveTexture the associated emissive texture used to generate the glow
  97628. * @return true if ready otherwise, false
  97629. */
  97630. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97631. var material = subMesh.getMaterial();
  97632. var mesh = subMesh.getRenderingMesh();
  97633. if (!material || !mesh) {
  97634. return false;
  97635. }
  97636. var emissiveTexture = material.emissiveTexture;
  97637. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97638. };
  97639. /**
  97640. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97641. */
  97642. GlowLayer.prototype.needStencil = function () {
  97643. return false;
  97644. };
  97645. /**
  97646. * Implementation specific of rendering the generating effect on the main canvas.
  97647. * @param effect The effect used to render through
  97648. */
  97649. GlowLayer.prototype._internalRender = function (effect) {
  97650. // Texture
  97651. effect.setTexture("textureSampler", this._blurTexture1);
  97652. effect.setTexture("textureSampler2", this._blurTexture2);
  97653. effect.setFloat("offset", this._intensity);
  97654. // Cache
  97655. var engine = this._engine;
  97656. var previousStencilBuffer = engine.getStencilBuffer();
  97657. // Draw order
  97658. engine.setStencilBuffer(false);
  97659. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97660. // Draw order
  97661. engine.setStencilBuffer(previousStencilBuffer);
  97662. };
  97663. /**
  97664. * Sets the required values for both the emissive texture and and the main color.
  97665. */
  97666. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97667. var textureLevel = 1.0;
  97668. if (this.customEmissiveTextureSelector) {
  97669. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97670. }
  97671. else {
  97672. if (material) {
  97673. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97674. if (this._emissiveTextureAndColor.texture) {
  97675. textureLevel = this._emissiveTextureAndColor.texture.level;
  97676. }
  97677. }
  97678. else {
  97679. this._emissiveTextureAndColor.texture = null;
  97680. }
  97681. }
  97682. if (this.customEmissiveColorSelector) {
  97683. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97684. }
  97685. else {
  97686. if (material.emissiveColor) {
  97687. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97688. }
  97689. else {
  97690. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97691. }
  97692. }
  97693. };
  97694. /**
  97695. * Returns true if the mesh should render, otherwise false.
  97696. * @param mesh The mesh to render
  97697. * @returns true if it should render otherwise false
  97698. */
  97699. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97700. return this.hasMesh(mesh);
  97701. };
  97702. /**
  97703. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97704. * @param mesh The mesh to exclude from the glow layer
  97705. */
  97706. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97707. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97708. this._excludedMeshes.push(mesh.uniqueId);
  97709. }
  97710. };
  97711. /**
  97712. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97713. * @param mesh The mesh to remove
  97714. */
  97715. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97716. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97717. if (index !== -1) {
  97718. this._excludedMeshes.splice(index, 1);
  97719. }
  97720. };
  97721. /**
  97722. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97723. * @param mesh The mesh to include in the glow layer
  97724. */
  97725. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97726. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97727. this._includedOnlyMeshes.push(mesh.uniqueId);
  97728. }
  97729. };
  97730. /**
  97731. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97732. * @param mesh The mesh to remove
  97733. */
  97734. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97735. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97736. if (index !== -1) {
  97737. this._includedOnlyMeshes.splice(index, 1);
  97738. }
  97739. };
  97740. /**
  97741. * Determine if a given mesh will be used in the glow layer
  97742. * @param mesh The mesh to test
  97743. * @returns true if the mesh will be highlighted by the current glow layer
  97744. */
  97745. GlowLayer.prototype.hasMesh = function (mesh) {
  97746. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97747. return false;
  97748. }
  97749. // Included Mesh
  97750. if (this._includedOnlyMeshes.length) {
  97751. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97752. }
  97753. ;
  97754. // Excluded Mesh
  97755. if (this._excludedMeshes.length) {
  97756. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97757. }
  97758. ;
  97759. return true;
  97760. };
  97761. /**
  97762. * Free any resources and references associated to a mesh.
  97763. * Internal use
  97764. * @param mesh The mesh to free.
  97765. */
  97766. GlowLayer.prototype._disposeMesh = function (mesh) {
  97767. this.removeIncludedOnlyMesh(mesh);
  97768. this.removeExcludedMesh(mesh);
  97769. };
  97770. /**
  97771. * Gets the class name of the effect layer
  97772. * @returns the string with the class name of the effect layer
  97773. */
  97774. GlowLayer.prototype.getClassName = function () {
  97775. return "GlowLayer";
  97776. };
  97777. /**
  97778. * Serializes this glow layer
  97779. * @returns a serialized glow layer object
  97780. */
  97781. GlowLayer.prototype.serialize = function () {
  97782. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97783. serializationObject.customType = "BABYLON.GlowLayer";
  97784. var index;
  97785. // Included meshes
  97786. serializationObject.includedMeshes = [];
  97787. if (this._includedOnlyMeshes.length) {
  97788. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97789. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97790. if (mesh) {
  97791. serializationObject.includedMeshes.push(mesh.id);
  97792. }
  97793. }
  97794. }
  97795. // Excluded meshes
  97796. serializationObject.excludedMeshes = [];
  97797. if (this._excludedMeshes.length) {
  97798. for (index = 0; index < this._excludedMeshes.length; index++) {
  97799. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97800. if (mesh) {
  97801. serializationObject.excludedMeshes.push(mesh.id);
  97802. }
  97803. }
  97804. }
  97805. return serializationObject;
  97806. };
  97807. /**
  97808. * Creates a Glow Layer from parsed glow layer data
  97809. * @param parsedGlowLayer defines glow layer data
  97810. * @param scene defines the current scene
  97811. * @param rootUrl defines the root URL containing the glow layer information
  97812. * @returns a parsed Glow Layer
  97813. */
  97814. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97815. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97816. var index;
  97817. // Excluded meshes
  97818. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97819. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97820. if (mesh) {
  97821. gl.addExcludedMesh(mesh);
  97822. }
  97823. }
  97824. // Included meshes
  97825. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97826. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97827. if (mesh) {
  97828. gl.addIncludedOnlyMesh(mesh);
  97829. }
  97830. }
  97831. return gl;
  97832. };
  97833. /**
  97834. * Effect Name of the layer.
  97835. */
  97836. GlowLayer.EffectName = "GlowLayer";
  97837. /**
  97838. * The default blur kernel size used for the glow.
  97839. */
  97840. GlowLayer.DefaultBlurKernelSize = 32;
  97841. /**
  97842. * The default texture size ratio used for the glow.
  97843. */
  97844. GlowLayer.DefaultTextureRatio = 0.5;
  97845. __decorate([
  97846. BABYLON.serialize()
  97847. ], GlowLayer.prototype, "blurKernelSize", null);
  97848. __decorate([
  97849. BABYLON.serialize()
  97850. ], GlowLayer.prototype, "intensity", null);
  97851. __decorate([
  97852. BABYLON.serialize("options")
  97853. ], GlowLayer.prototype, "_options", void 0);
  97854. return GlowLayer;
  97855. }(BABYLON.EffectLayer));
  97856. BABYLON.GlowLayer = GlowLayer;
  97857. })(BABYLON || (BABYLON = {}));
  97858. //# sourceMappingURL=babylon.glowLayer.js.map
  97859. var BABYLON;
  97860. (function (BABYLON) {
  97861. /**
  97862. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97863. */
  97864. var AssetTaskState;
  97865. (function (AssetTaskState) {
  97866. /**
  97867. * Initialization
  97868. */
  97869. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97870. /**
  97871. * Running
  97872. */
  97873. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97874. /**
  97875. * Done
  97876. */
  97877. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97878. /**
  97879. * Error
  97880. */
  97881. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97882. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97883. /**
  97884. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97885. */
  97886. var AbstractAssetTask = /** @class */ (function () {
  97887. /**
  97888. * Creates a new {BABYLON.AssetsManager}
  97889. * @param name defines the name of the task
  97890. */
  97891. function AbstractAssetTask(
  97892. /**
  97893. * Task name
  97894. */ name) {
  97895. this.name = name;
  97896. this._isCompleted = false;
  97897. this._taskState = AssetTaskState.INIT;
  97898. }
  97899. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97900. /**
  97901. * Get if the task is completed
  97902. */
  97903. get: function () {
  97904. return this._isCompleted;
  97905. },
  97906. enumerable: true,
  97907. configurable: true
  97908. });
  97909. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97910. /**
  97911. * Gets the current state of the task
  97912. */
  97913. get: function () {
  97914. return this._taskState;
  97915. },
  97916. enumerable: true,
  97917. configurable: true
  97918. });
  97919. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97920. /**
  97921. * Gets the current error object (if task is in error)
  97922. */
  97923. get: function () {
  97924. return this._errorObject;
  97925. },
  97926. enumerable: true,
  97927. configurable: true
  97928. });
  97929. /**
  97930. * Internal only
  97931. * @hidden
  97932. */
  97933. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97934. if (this._errorObject) {
  97935. return;
  97936. }
  97937. this._errorObject = {
  97938. message: message,
  97939. exception: exception
  97940. };
  97941. };
  97942. /**
  97943. * Execute the current task
  97944. * @param scene defines the scene where you want your assets to be loaded
  97945. * @param onSuccess is a callback called when the task is successfully executed
  97946. * @param onError is a callback called if an error occurs
  97947. */
  97948. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97949. var _this = this;
  97950. this._taskState = AssetTaskState.RUNNING;
  97951. this.runTask(scene, function () {
  97952. _this.onDoneCallback(onSuccess, onError);
  97953. }, function (msg, exception) {
  97954. _this.onErrorCallback(onError, msg, exception);
  97955. });
  97956. };
  97957. /**
  97958. * Execute the current task
  97959. * @param scene defines the scene where you want your assets to be loaded
  97960. * @param onSuccess is a callback called when the task is successfully executed
  97961. * @param onError is a callback called if an error occurs
  97962. */
  97963. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97964. throw new Error("runTask is not implemented");
  97965. };
  97966. /**
  97967. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  97968. * This can be used with failed tasks that have the reason for failure fixed.
  97969. */
  97970. AbstractAssetTask.prototype.reset = function () {
  97971. this._taskState = AssetTaskState.INIT;
  97972. };
  97973. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  97974. this._taskState = AssetTaskState.ERROR;
  97975. this._errorObject = {
  97976. message: message,
  97977. exception: exception
  97978. };
  97979. if (this.onError) {
  97980. this.onError(this, message, exception);
  97981. }
  97982. onError();
  97983. };
  97984. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  97985. try {
  97986. this._taskState = AssetTaskState.DONE;
  97987. this._isCompleted = true;
  97988. if (this.onSuccess) {
  97989. this.onSuccess(this);
  97990. }
  97991. onSuccess();
  97992. }
  97993. catch (e) {
  97994. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  97995. }
  97996. };
  97997. return AbstractAssetTask;
  97998. }());
  97999. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98000. /**
  98001. * Class used to share progress information about assets loading
  98002. */
  98003. var AssetsProgressEvent = /** @class */ (function () {
  98004. /**
  98005. * Creates a {BABYLON.AssetsProgressEvent}
  98006. * @param remainingCount defines the number of remaining tasks to process
  98007. * @param totalCount defines the total number of tasks
  98008. * @param task defines the task that was just processed
  98009. */
  98010. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98011. this.remainingCount = remainingCount;
  98012. this.totalCount = totalCount;
  98013. this.task = task;
  98014. }
  98015. return AssetsProgressEvent;
  98016. }());
  98017. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98018. /**
  98019. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98020. */
  98021. var MeshAssetTask = /** @class */ (function (_super) {
  98022. __extends(MeshAssetTask, _super);
  98023. /**
  98024. * Creates a new {BABYLON.MeshAssetTask}
  98025. * @param name defines the name of the task
  98026. * @param meshesNames defines the list of mesh's names you want to load
  98027. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98028. * @param sceneFilename defines the filename of the scene to load from
  98029. */
  98030. function MeshAssetTask(
  98031. /**
  98032. * Defines the name of the task
  98033. */
  98034. name,
  98035. /**
  98036. * Defines the list of mesh's names you want to load
  98037. */
  98038. meshesNames,
  98039. /**
  98040. * Defines the root url to use as a base to load your meshes and associated resources
  98041. */
  98042. rootUrl,
  98043. /**
  98044. * Defines the filename of the scene to load from
  98045. */
  98046. sceneFilename) {
  98047. var _this = _super.call(this, name) || this;
  98048. _this.name = name;
  98049. _this.meshesNames = meshesNames;
  98050. _this.rootUrl = rootUrl;
  98051. _this.sceneFilename = sceneFilename;
  98052. return _this;
  98053. }
  98054. /**
  98055. * Execute the current task
  98056. * @param scene defines the scene where you want your assets to be loaded
  98057. * @param onSuccess is a callback called when the task is successfully executed
  98058. * @param onError is a callback called if an error occurs
  98059. */
  98060. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98061. var _this = this;
  98062. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98063. _this.loadedMeshes = meshes;
  98064. _this.loadedParticleSystems = particleSystems;
  98065. _this.loadedSkeletons = skeletons;
  98066. onSuccess();
  98067. }, null, function (scene, message, exception) {
  98068. onError(message, exception);
  98069. });
  98070. };
  98071. return MeshAssetTask;
  98072. }(AbstractAssetTask));
  98073. BABYLON.MeshAssetTask = MeshAssetTask;
  98074. /**
  98075. * Define a task used by {BABYLON.AssetsManager} to load text content
  98076. */
  98077. var TextFileAssetTask = /** @class */ (function (_super) {
  98078. __extends(TextFileAssetTask, _super);
  98079. /**
  98080. * Creates a new TextFileAssetTask object
  98081. * @param name defines the name of the task
  98082. * @param url defines the location of the file to load
  98083. */
  98084. function TextFileAssetTask(
  98085. /**
  98086. * Defines the name of the task
  98087. */
  98088. name,
  98089. /**
  98090. * Defines the location of the file to load
  98091. */
  98092. url) {
  98093. var _this = _super.call(this, name) || this;
  98094. _this.name = name;
  98095. _this.url = url;
  98096. return _this;
  98097. }
  98098. /**
  98099. * Execute the current task
  98100. * @param scene defines the scene where you want your assets to be loaded
  98101. * @param onSuccess is a callback called when the task is successfully executed
  98102. * @param onError is a callback called if an error occurs
  98103. */
  98104. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98105. var _this = this;
  98106. scene._loadFile(this.url, function (data) {
  98107. _this.text = data;
  98108. onSuccess();
  98109. }, undefined, false, false, function (request, exception) {
  98110. if (request) {
  98111. onError(request.status + " " + request.statusText, exception);
  98112. }
  98113. });
  98114. };
  98115. return TextFileAssetTask;
  98116. }(AbstractAssetTask));
  98117. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98118. /**
  98119. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98120. */
  98121. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98122. __extends(BinaryFileAssetTask, _super);
  98123. /**
  98124. * Creates a new BinaryFileAssetTask object
  98125. * @param name defines the name of the new task
  98126. * @param url defines the location of the file to load
  98127. */
  98128. function BinaryFileAssetTask(
  98129. /**
  98130. * Defines the name of the task
  98131. */
  98132. name,
  98133. /**
  98134. * Defines the location of the file to load
  98135. */
  98136. url) {
  98137. var _this = _super.call(this, name) || this;
  98138. _this.name = name;
  98139. _this.url = url;
  98140. return _this;
  98141. }
  98142. /**
  98143. * Execute the current task
  98144. * @param scene defines the scene where you want your assets to be loaded
  98145. * @param onSuccess is a callback called when the task is successfully executed
  98146. * @param onError is a callback called if an error occurs
  98147. */
  98148. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98149. var _this = this;
  98150. scene._loadFile(this.url, function (data) {
  98151. _this.data = data;
  98152. onSuccess();
  98153. }, undefined, true, true, function (request, exception) {
  98154. if (request) {
  98155. onError(request.status + " " + request.statusText, exception);
  98156. }
  98157. });
  98158. };
  98159. return BinaryFileAssetTask;
  98160. }(AbstractAssetTask));
  98161. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98162. /**
  98163. * Define a task used by {BABYLON.AssetsManager} to load images
  98164. */
  98165. var ImageAssetTask = /** @class */ (function (_super) {
  98166. __extends(ImageAssetTask, _super);
  98167. /**
  98168. * Creates a new ImageAssetTask
  98169. * @param name defines the name of the task
  98170. * @param url defines the location of the image to load
  98171. */
  98172. function ImageAssetTask(
  98173. /**
  98174. * Defines the name of the task
  98175. */
  98176. name,
  98177. /**
  98178. * Defines the location of the image to load
  98179. */
  98180. url) {
  98181. var _this = _super.call(this, name) || this;
  98182. _this.name = name;
  98183. _this.url = url;
  98184. return _this;
  98185. }
  98186. /**
  98187. * Execute the current task
  98188. * @param scene defines the scene where you want your assets to be loaded
  98189. * @param onSuccess is a callback called when the task is successfully executed
  98190. * @param onError is a callback called if an error occurs
  98191. */
  98192. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98193. var _this = this;
  98194. var img = new Image();
  98195. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98196. img.onload = function () {
  98197. _this.image = img;
  98198. onSuccess();
  98199. };
  98200. img.onerror = function (err) {
  98201. onError("Error loading image", err);
  98202. };
  98203. img.src = this.url;
  98204. };
  98205. return ImageAssetTask;
  98206. }(AbstractAssetTask));
  98207. BABYLON.ImageAssetTask = ImageAssetTask;
  98208. /**
  98209. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98210. */
  98211. var TextureAssetTask = /** @class */ (function (_super) {
  98212. __extends(TextureAssetTask, _super);
  98213. /**
  98214. * Creates a new TextureAssetTask object
  98215. * @param name defines the name of the task
  98216. * @param url defines the location of the file to load
  98217. * @param noMipmap defines if mipmap should not be generated (default is false)
  98218. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98219. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98220. */
  98221. function TextureAssetTask(
  98222. /**
  98223. * Defines the name of the task
  98224. */
  98225. name,
  98226. /**
  98227. * Defines the location of the file to load
  98228. */
  98229. url,
  98230. /**
  98231. * Defines if mipmap should not be generated (default is false)
  98232. */
  98233. noMipmap,
  98234. /**
  98235. * Defines if texture must be inverted on Y axis (default is false)
  98236. */
  98237. invertY,
  98238. /**
  98239. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98240. */
  98241. samplingMode) {
  98242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98243. var _this = _super.call(this, name) || this;
  98244. _this.name = name;
  98245. _this.url = url;
  98246. _this.noMipmap = noMipmap;
  98247. _this.invertY = invertY;
  98248. _this.samplingMode = samplingMode;
  98249. return _this;
  98250. }
  98251. /**
  98252. * Execute the current task
  98253. * @param scene defines the scene where you want your assets to be loaded
  98254. * @param onSuccess is a callback called when the task is successfully executed
  98255. * @param onError is a callback called if an error occurs
  98256. */
  98257. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98258. var onload = function () {
  98259. onSuccess();
  98260. };
  98261. var onerror = function (message, exception) {
  98262. onError(message, exception);
  98263. };
  98264. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98265. };
  98266. return TextureAssetTask;
  98267. }(AbstractAssetTask));
  98268. BABYLON.TextureAssetTask = TextureAssetTask;
  98269. /**
  98270. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98271. */
  98272. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98273. __extends(CubeTextureAssetTask, _super);
  98274. /**
  98275. * Creates a new CubeTextureAssetTask
  98276. * @param name defines the name of the task
  98277. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98278. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98279. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98280. * @param files defines the explicit list of files (undefined by default)
  98281. */
  98282. function CubeTextureAssetTask(
  98283. /**
  98284. * Defines the name of the task
  98285. */
  98286. name,
  98287. /**
  98288. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98289. */
  98290. url,
  98291. /**
  98292. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98293. */
  98294. extensions,
  98295. /**
  98296. * Defines if mipmaps should not be generated (default is false)
  98297. */
  98298. noMipmap,
  98299. /**
  98300. * Defines the explicit list of files (undefined by default)
  98301. */
  98302. files) {
  98303. var _this = _super.call(this, name) || this;
  98304. _this.name = name;
  98305. _this.url = url;
  98306. _this.extensions = extensions;
  98307. _this.noMipmap = noMipmap;
  98308. _this.files = files;
  98309. return _this;
  98310. }
  98311. /**
  98312. * Execute the current task
  98313. * @param scene defines the scene where you want your assets to be loaded
  98314. * @param onSuccess is a callback called when the task is successfully executed
  98315. * @param onError is a callback called if an error occurs
  98316. */
  98317. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98318. var onload = function () {
  98319. onSuccess();
  98320. };
  98321. var onerror = function (message, exception) {
  98322. onError(message, exception);
  98323. };
  98324. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98325. };
  98326. return CubeTextureAssetTask;
  98327. }(AbstractAssetTask));
  98328. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98329. /**
  98330. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98331. */
  98332. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98333. __extends(HDRCubeTextureAssetTask, _super);
  98334. /**
  98335. * Creates a new HDRCubeTextureAssetTask object
  98336. * @param name defines the name of the task
  98337. * @param url defines the location of the file to load
  98338. * @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.
  98339. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98340. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98341. * @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)
  98342. * @param reserved Internal use only
  98343. */
  98344. function HDRCubeTextureAssetTask(
  98345. /**
  98346. * Defines the name of the task
  98347. */
  98348. name,
  98349. /**
  98350. * Defines the location of the file to load
  98351. */
  98352. url,
  98353. /**
  98354. * Defines the desired size (the more it increases the longer the generation will be)
  98355. */
  98356. size,
  98357. /**
  98358. * Defines if mipmaps should not be generated (default is false)
  98359. */
  98360. noMipmap,
  98361. /**
  98362. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98363. */
  98364. generateHarmonics,
  98365. /**
  98366. * 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)
  98367. */
  98368. gammaSpace,
  98369. /**
  98370. * Internal Use Only
  98371. */
  98372. reserved) {
  98373. if (noMipmap === void 0) { noMipmap = false; }
  98374. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98375. if (gammaSpace === void 0) { gammaSpace = false; }
  98376. if (reserved === void 0) { reserved = false; }
  98377. var _this = _super.call(this, name) || this;
  98378. _this.name = name;
  98379. _this.url = url;
  98380. _this.size = size;
  98381. _this.noMipmap = noMipmap;
  98382. _this.generateHarmonics = generateHarmonics;
  98383. _this.gammaSpace = gammaSpace;
  98384. _this.reserved = reserved;
  98385. return _this;
  98386. }
  98387. /**
  98388. * Execute the current task
  98389. * @param scene defines the scene where you want your assets to be loaded
  98390. * @param onSuccess is a callback called when the task is successfully executed
  98391. * @param onError is a callback called if an error occurs
  98392. */
  98393. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98394. var onload = function () {
  98395. onSuccess();
  98396. };
  98397. var onerror = function (message, exception) {
  98398. onError(message, exception);
  98399. };
  98400. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98401. };
  98402. return HDRCubeTextureAssetTask;
  98403. }(AbstractAssetTask));
  98404. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98405. /**
  98406. * This class can be used to easily import assets into a scene
  98407. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98408. */
  98409. var AssetsManager = /** @class */ (function () {
  98410. /**
  98411. * Creates a new AssetsManager
  98412. * @param scene defines the scene to work on
  98413. */
  98414. function AssetsManager(scene) {
  98415. this._isLoading = false;
  98416. this._tasks = new Array();
  98417. this._waitingTasksCount = 0;
  98418. this._totalTasksCount = 0;
  98419. /**
  98420. * Observable called when all tasks are processed
  98421. */
  98422. this.onTaskSuccessObservable = new BABYLON.Observable();
  98423. /**
  98424. * Observable called when a task had an error
  98425. */
  98426. this.onTaskErrorObservable = new BABYLON.Observable();
  98427. /**
  98428. * Observable called when a task is successful
  98429. */
  98430. this.onTasksDoneObservable = new BABYLON.Observable();
  98431. /**
  98432. * Observable called when a task is done (whatever the result is)
  98433. */
  98434. this.onProgressObservable = new BABYLON.Observable();
  98435. /**
  98436. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98437. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98438. */
  98439. this.useDefaultLoadingScreen = true;
  98440. this._scene = scene;
  98441. }
  98442. /**
  98443. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98444. * @param taskName defines the name of the new task
  98445. * @param meshesNames defines the name of meshes to load
  98446. * @param rootUrl defines the root url to use to locate files
  98447. * @param sceneFilename defines the filename of the scene file
  98448. * @returns a new {BABYLON.MeshAssetTask} object
  98449. */
  98450. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98451. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98452. this._tasks.push(task);
  98453. return task;
  98454. };
  98455. /**
  98456. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98457. * @param taskName defines the name of the new task
  98458. * @param url defines the url of the file to load
  98459. * @returns a new {BABYLON.TextFileAssetTask} object
  98460. */
  98461. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98462. var task = new TextFileAssetTask(taskName, url);
  98463. this._tasks.push(task);
  98464. return task;
  98465. };
  98466. /**
  98467. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98468. * @param taskName defines the name of the new task
  98469. * @param url defines the url of the file to load
  98470. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98471. */
  98472. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98473. var task = new BinaryFileAssetTask(taskName, url);
  98474. this._tasks.push(task);
  98475. return task;
  98476. };
  98477. /**
  98478. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98479. * @param taskName defines the name of the new task
  98480. * @param url defines the url of the file to load
  98481. * @returns a new {BABYLON.ImageAssetTask} object
  98482. */
  98483. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98484. var task = new ImageAssetTask(taskName, url);
  98485. this._tasks.push(task);
  98486. return task;
  98487. };
  98488. /**
  98489. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98490. * @param taskName defines the name of the new task
  98491. * @param url defines the url of the file to load
  98492. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98493. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98494. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98495. * @returns a new {BABYLON.TextureAssetTask} object
  98496. */
  98497. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98499. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98500. this._tasks.push(task);
  98501. return task;
  98502. };
  98503. /**
  98504. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98505. * @param taskName defines the name of the new task
  98506. * @param url defines the url of the file to load
  98507. * @param extensions defines the extension to use to load the cube map (can be null)
  98508. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98509. * @param files defines the list of files to load (can be null)
  98510. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98511. */
  98512. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98513. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98514. this._tasks.push(task);
  98515. return task;
  98516. };
  98517. /**
  98518. *
  98519. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98520. * @param taskName defines the name of the new task
  98521. * @param url defines the url of the file to load
  98522. * @param size defines the size you want for the cubemap (can be null)
  98523. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98524. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98525. * @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)
  98526. * @param reserved Internal use only
  98527. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98528. */
  98529. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98530. if (noMipmap === void 0) { noMipmap = false; }
  98531. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98532. if (gammaSpace === void 0) { gammaSpace = false; }
  98533. if (reserved === void 0) { reserved = false; }
  98534. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98535. this._tasks.push(task);
  98536. return task;
  98537. };
  98538. /**
  98539. * Remove a task from the assets manager.
  98540. * @param task the task to remove
  98541. */
  98542. AssetsManager.prototype.removeTask = function (task) {
  98543. var index = this._tasks.indexOf(task);
  98544. if (index > -1) {
  98545. this._tasks.splice(index, 1);
  98546. }
  98547. };
  98548. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98549. this._waitingTasksCount--;
  98550. try {
  98551. if (this.onProgress) {
  98552. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98553. }
  98554. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98555. }
  98556. catch (e) {
  98557. BABYLON.Tools.Error("Error running progress callbacks.");
  98558. console.log(e);
  98559. }
  98560. if (this._waitingTasksCount === 0) {
  98561. try {
  98562. if (this.onFinish) {
  98563. this.onFinish(this._tasks);
  98564. }
  98565. // Let's remove successfull tasks
  98566. var currentTasks = this._tasks.slice();
  98567. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98568. var task = currentTasks_1[_i];
  98569. if (task.taskState === AssetTaskState.DONE) {
  98570. var index = this._tasks.indexOf(task);
  98571. if (index > -1) {
  98572. this._tasks.splice(index, 1);
  98573. }
  98574. }
  98575. }
  98576. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98577. }
  98578. catch (e) {
  98579. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98580. console.log(e);
  98581. }
  98582. this._isLoading = false;
  98583. this._scene.getEngine().hideLoadingUI();
  98584. }
  98585. };
  98586. AssetsManager.prototype._runTask = function (task) {
  98587. var _this = this;
  98588. var done = function () {
  98589. try {
  98590. if (_this.onTaskSuccess) {
  98591. _this.onTaskSuccess(task);
  98592. }
  98593. _this.onTaskSuccessObservable.notifyObservers(task);
  98594. _this._decreaseWaitingTasksCount(task);
  98595. }
  98596. catch (e) {
  98597. error("Error executing task success callbacks", e);
  98598. }
  98599. };
  98600. var error = function (message, exception) {
  98601. task._setErrorObject(message, exception);
  98602. if (_this.onTaskError) {
  98603. _this.onTaskError(task);
  98604. }
  98605. _this.onTaskErrorObservable.notifyObservers(task);
  98606. _this._decreaseWaitingTasksCount(task);
  98607. };
  98608. task.run(this._scene, done, error);
  98609. };
  98610. /**
  98611. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98612. * @return the current instance of the {BABYLON.AssetsManager}
  98613. */
  98614. AssetsManager.prototype.reset = function () {
  98615. this._isLoading = false;
  98616. this._tasks = new Array();
  98617. return this;
  98618. };
  98619. /**
  98620. * Start the loading process
  98621. * @return the current instance of the {BABYLON.AssetsManager}
  98622. */
  98623. AssetsManager.prototype.load = function () {
  98624. if (this._isLoading) {
  98625. return this;
  98626. }
  98627. this._isLoading = true;
  98628. this._waitingTasksCount = this._tasks.length;
  98629. this._totalTasksCount = this._tasks.length;
  98630. if (this._waitingTasksCount === 0) {
  98631. this._isLoading = false;
  98632. if (this.onFinish) {
  98633. this.onFinish(this._tasks);
  98634. }
  98635. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98636. return this;
  98637. }
  98638. if (this.useDefaultLoadingScreen) {
  98639. this._scene.getEngine().displayLoadingUI();
  98640. }
  98641. for (var index = 0; index < this._tasks.length; index++) {
  98642. var task = this._tasks[index];
  98643. if (task.taskState === AssetTaskState.INIT) {
  98644. this._runTask(task);
  98645. }
  98646. }
  98647. return this;
  98648. };
  98649. return AssetsManager;
  98650. }());
  98651. BABYLON.AssetsManager = AssetsManager;
  98652. })(BABYLON || (BABYLON = {}));
  98653. //# sourceMappingURL=babylon.assetsManager.js.map
  98654. var BABYLON;
  98655. (function (BABYLON) {
  98656. var serializedGeometries = [];
  98657. var serializeGeometry = function (geometry, serializationGeometries) {
  98658. if (serializedGeometries[geometry.id]) {
  98659. return;
  98660. }
  98661. if (geometry.doNotSerialize) {
  98662. return;
  98663. }
  98664. if (geometry instanceof BABYLON.BoxGeometry) {
  98665. serializationGeometries.boxes.push(geometry.serialize());
  98666. }
  98667. else if (geometry instanceof BABYLON.SphereGeometry) {
  98668. serializationGeometries.spheres.push(geometry.serialize());
  98669. }
  98670. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98671. serializationGeometries.cylinders.push(geometry.serialize());
  98672. }
  98673. else if (geometry instanceof BABYLON.TorusGeometry) {
  98674. serializationGeometries.toruses.push(geometry.serialize());
  98675. }
  98676. else if (geometry instanceof BABYLON.GroundGeometry) {
  98677. serializationGeometries.grounds.push(geometry.serialize());
  98678. }
  98679. else if (geometry instanceof BABYLON.Plane) {
  98680. serializationGeometries.planes.push(geometry.serialize());
  98681. }
  98682. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98683. serializationGeometries.torusKnots.push(geometry.serialize());
  98684. }
  98685. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98686. throw new Error("Unknown primitive type");
  98687. }
  98688. else {
  98689. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98690. }
  98691. serializedGeometries[geometry.id] = true;
  98692. };
  98693. var serializeMesh = function (mesh, serializationScene) {
  98694. var serializationObject = {};
  98695. // Geometry
  98696. var geometry = mesh._geometry;
  98697. if (geometry) {
  98698. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98699. // 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
  98700. serializeGeometry(geometry, serializationScene.geometries);
  98701. }
  98702. }
  98703. // Custom
  98704. if (mesh.serialize) {
  98705. mesh.serialize(serializationObject);
  98706. }
  98707. return serializationObject;
  98708. };
  98709. var finalizeSingleMesh = function (mesh, serializationObject) {
  98710. //only works if the mesh is already loaded
  98711. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98712. //serialize material
  98713. if (mesh.material) {
  98714. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98715. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98716. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98717. serializationObject.multiMaterials.push(mesh.material.serialize());
  98718. }
  98719. }
  98720. else {
  98721. serializationObject.materials = serializationObject.materials || [];
  98722. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98723. serializationObject.materials.push(mesh.material.serialize());
  98724. }
  98725. }
  98726. }
  98727. //serialize geometry
  98728. var geometry = mesh._geometry;
  98729. if (geometry) {
  98730. if (!serializationObject.geometries) {
  98731. serializationObject.geometries = {};
  98732. serializationObject.geometries.boxes = [];
  98733. serializationObject.geometries.spheres = [];
  98734. serializationObject.geometries.cylinders = [];
  98735. serializationObject.geometries.toruses = [];
  98736. serializationObject.geometries.grounds = [];
  98737. serializationObject.geometries.planes = [];
  98738. serializationObject.geometries.torusKnots = [];
  98739. serializationObject.geometries.vertexData = [];
  98740. }
  98741. serializeGeometry(geometry, serializationObject.geometries);
  98742. }
  98743. // Skeletons
  98744. if (mesh.skeleton) {
  98745. serializationObject.skeletons = serializationObject.skeletons || [];
  98746. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98747. }
  98748. //serialize the actual mesh
  98749. serializationObject.meshes = serializationObject.meshes || [];
  98750. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98751. }
  98752. };
  98753. var SceneSerializer = /** @class */ (function () {
  98754. function SceneSerializer() {
  98755. }
  98756. SceneSerializer.ClearCache = function () {
  98757. serializedGeometries = [];
  98758. };
  98759. SceneSerializer.Serialize = function (scene) {
  98760. var serializationObject = {};
  98761. SceneSerializer.ClearCache();
  98762. // Scene
  98763. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98764. serializationObject.autoClear = scene.autoClear;
  98765. serializationObject.clearColor = scene.clearColor.asArray();
  98766. serializationObject.ambientColor = scene.ambientColor.asArray();
  98767. serializationObject.gravity = scene.gravity.asArray();
  98768. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98769. serializationObject.workerCollisions = scene.workerCollisions;
  98770. // Fog
  98771. if (scene.fogMode && scene.fogMode !== 0) {
  98772. serializationObject.fogMode = scene.fogMode;
  98773. serializationObject.fogColor = scene.fogColor.asArray();
  98774. serializationObject.fogStart = scene.fogStart;
  98775. serializationObject.fogEnd = scene.fogEnd;
  98776. serializationObject.fogDensity = scene.fogDensity;
  98777. }
  98778. //Physics
  98779. if (scene.isPhysicsEnabled()) {
  98780. var physicEngine = scene.getPhysicsEngine();
  98781. if (physicEngine) {
  98782. serializationObject.physicsEnabled = true;
  98783. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98784. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98785. }
  98786. }
  98787. // Metadata
  98788. if (scene.metadata) {
  98789. serializationObject.metadata = scene.metadata;
  98790. }
  98791. // Morph targets
  98792. serializationObject.morphTargetManagers = [];
  98793. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98794. var abstractMesh = _a[_i];
  98795. var manager = abstractMesh.morphTargetManager;
  98796. if (manager) {
  98797. serializationObject.morphTargetManagers.push(manager.serialize());
  98798. }
  98799. }
  98800. // Lights
  98801. serializationObject.lights = [];
  98802. var index;
  98803. var light;
  98804. for (index = 0; index < scene.lights.length; index++) {
  98805. light = scene.lights[index];
  98806. if (!light.doNotSerialize) {
  98807. serializationObject.lights.push(light.serialize());
  98808. }
  98809. }
  98810. // Cameras
  98811. serializationObject.cameras = [];
  98812. for (index = 0; index < scene.cameras.length; index++) {
  98813. var camera = scene.cameras[index];
  98814. if (!camera.doNotSerialize) {
  98815. serializationObject.cameras.push(camera.serialize());
  98816. }
  98817. }
  98818. if (scene.activeCamera) {
  98819. serializationObject.activeCameraID = scene.activeCamera.id;
  98820. }
  98821. // Animations
  98822. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98823. // Materials
  98824. serializationObject.materials = [];
  98825. serializationObject.multiMaterials = [];
  98826. var material;
  98827. for (index = 0; index < scene.materials.length; index++) {
  98828. material = scene.materials[index];
  98829. if (!material.doNotSerialize) {
  98830. serializationObject.materials.push(material.serialize());
  98831. }
  98832. }
  98833. // MultiMaterials
  98834. serializationObject.multiMaterials = [];
  98835. for (index = 0; index < scene.multiMaterials.length; index++) {
  98836. var multiMaterial = scene.multiMaterials[index];
  98837. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98838. }
  98839. // Environment texture
  98840. if (scene.environmentTexture) {
  98841. serializationObject.environmentTexture = scene.environmentTexture.name;
  98842. }
  98843. // Skeletons
  98844. serializationObject.skeletons = [];
  98845. for (index = 0; index < scene.skeletons.length; index++) {
  98846. var skeleton = scene.skeletons[index];
  98847. if (!skeleton.doNotSerialize) {
  98848. serializationObject.skeletons.push(skeleton.serialize());
  98849. }
  98850. }
  98851. // Transform nodes
  98852. serializationObject.transformNodes = [];
  98853. for (index = 0; index < scene.transformNodes.length; index++) {
  98854. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98855. }
  98856. // Geometries
  98857. serializationObject.geometries = {};
  98858. serializationObject.geometries.boxes = [];
  98859. serializationObject.geometries.spheres = [];
  98860. serializationObject.geometries.cylinders = [];
  98861. serializationObject.geometries.toruses = [];
  98862. serializationObject.geometries.grounds = [];
  98863. serializationObject.geometries.planes = [];
  98864. serializationObject.geometries.torusKnots = [];
  98865. serializationObject.geometries.vertexData = [];
  98866. serializedGeometries = [];
  98867. var geometries = scene.getGeometries();
  98868. for (index = 0; index < geometries.length; index++) {
  98869. var geometry = geometries[index];
  98870. if (geometry.isReady()) {
  98871. serializeGeometry(geometry, serializationObject.geometries);
  98872. }
  98873. }
  98874. // Meshes
  98875. serializationObject.meshes = [];
  98876. for (index = 0; index < scene.meshes.length; index++) {
  98877. var abstractMesh = scene.meshes[index];
  98878. if (abstractMesh instanceof BABYLON.Mesh) {
  98879. var mesh = abstractMesh;
  98880. if (!mesh.doNotSerialize) {
  98881. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98882. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98883. }
  98884. }
  98885. }
  98886. }
  98887. // Particles Systems
  98888. serializationObject.particleSystems = [];
  98889. for (index = 0; index < scene.particleSystems.length; index++) {
  98890. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98891. }
  98892. // Shadows
  98893. serializationObject.shadowGenerators = [];
  98894. for (index = 0; index < scene.lights.length; index++) {
  98895. light = scene.lights[index];
  98896. var shadowGenerator = light.getShadowGenerator();
  98897. if (shadowGenerator) {
  98898. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98899. }
  98900. }
  98901. // Action Manager
  98902. if (scene.actionManager) {
  98903. serializationObject.actions = scene.actionManager.serialize("scene");
  98904. }
  98905. // Audio
  98906. serializationObject.sounds = [];
  98907. for (index = 0; index < scene.soundTracks.length; index++) {
  98908. var soundtrack = scene.soundTracks[index];
  98909. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98910. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98911. }
  98912. }
  98913. // Components
  98914. for (var _b = 0, _c = scene._components; _b < _c.length; _b++) {
  98915. var component = _c[_b];
  98916. component.serialize(serializationObject);
  98917. }
  98918. return serializationObject;
  98919. };
  98920. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98921. if (withParents === void 0) { withParents = false; }
  98922. if (withChildren === void 0) { withChildren = false; }
  98923. var serializationObject = {};
  98924. SceneSerializer.ClearCache();
  98925. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98926. if (withParents || withChildren) {
  98927. //deliberate for loop! not for each, appended should be processed as well.
  98928. for (var i = 0; i < toSerialize.length; ++i) {
  98929. if (withChildren) {
  98930. toSerialize[i].getDescendants().forEach(function (node) {
  98931. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98932. toSerialize.push(node);
  98933. }
  98934. });
  98935. }
  98936. //make sure the array doesn't contain the object already
  98937. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98938. toSerialize.push(toSerialize[i].parent);
  98939. }
  98940. }
  98941. }
  98942. toSerialize.forEach(function (mesh) {
  98943. finalizeSingleMesh(mesh, serializationObject);
  98944. });
  98945. return serializationObject;
  98946. };
  98947. return SceneSerializer;
  98948. }());
  98949. BABYLON.SceneSerializer = SceneSerializer;
  98950. })(BABYLON || (BABYLON = {}));
  98951. //# sourceMappingURL=babylon.sceneSerializer.js.map
  98952. var BABYLON;
  98953. (function (BABYLON) {
  98954. var ReflectionProbe = /** @class */ (function () {
  98955. function ReflectionProbe(name, size, scene, generateMipMaps) {
  98956. if (generateMipMaps === void 0) { generateMipMaps = true; }
  98957. var _this = this;
  98958. this.name = name;
  98959. this._viewMatrix = BABYLON.Matrix.Identity();
  98960. this._target = BABYLON.Vector3.Zero();
  98961. this._add = BABYLON.Vector3.Zero();
  98962. this._invertYAxis = false;
  98963. this.position = BABYLON.Vector3.Zero();
  98964. this._scene = scene;
  98965. this._scene.reflectionProbes.push(this);
  98966. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98967. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98968. switch (faceIndex) {
  98969. case 0:
  98970. _this._add.copyFromFloats(1, 0, 0);
  98971. break;
  98972. case 1:
  98973. _this._add.copyFromFloats(-1, 0, 0);
  98974. break;
  98975. case 2:
  98976. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  98977. break;
  98978. case 3:
  98979. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  98980. break;
  98981. case 4:
  98982. _this._add.copyFromFloats(0, 0, 1);
  98983. break;
  98984. case 5:
  98985. _this._add.copyFromFloats(0, 0, -1);
  98986. break;
  98987. }
  98988. if (_this._attachedMesh) {
  98989. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  98990. }
  98991. _this.position.addToRef(_this._add, _this._target);
  98992. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  98993. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  98994. scene._forcedViewPosition = _this.position;
  98995. });
  98996. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  98997. scene._forcedViewPosition = null;
  98998. scene.updateTransformMatrix(true);
  98999. });
  99000. if (scene.activeCamera) {
  99001. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99002. }
  99003. }
  99004. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99005. get: function () {
  99006. return this._renderTargetTexture.samples;
  99007. },
  99008. set: function (value) {
  99009. this._renderTargetTexture.samples = value;
  99010. },
  99011. enumerable: true,
  99012. configurable: true
  99013. });
  99014. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99015. get: function () {
  99016. return this._renderTargetTexture.refreshRate;
  99017. },
  99018. set: function (value) {
  99019. this._renderTargetTexture.refreshRate = value;
  99020. },
  99021. enumerable: true,
  99022. configurable: true
  99023. });
  99024. ReflectionProbe.prototype.getScene = function () {
  99025. return this._scene;
  99026. };
  99027. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99028. get: function () {
  99029. return this._renderTargetTexture;
  99030. },
  99031. enumerable: true,
  99032. configurable: true
  99033. });
  99034. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99035. get: function () {
  99036. return this._renderTargetTexture.renderList;
  99037. },
  99038. enumerable: true,
  99039. configurable: true
  99040. });
  99041. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99042. this._attachedMesh = mesh;
  99043. };
  99044. /**
  99045. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99046. *
  99047. * @param renderingGroupId The rendering group id corresponding to its index
  99048. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99049. */
  99050. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99051. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99052. };
  99053. ReflectionProbe.prototype.dispose = function () {
  99054. var index = this._scene.reflectionProbes.indexOf(this);
  99055. if (index !== -1) {
  99056. // Remove from the scene if found
  99057. this._scene.reflectionProbes.splice(index, 1);
  99058. }
  99059. if (this._renderTargetTexture) {
  99060. this._renderTargetTexture.dispose();
  99061. this._renderTargetTexture = null;
  99062. }
  99063. };
  99064. return ReflectionProbe;
  99065. }());
  99066. BABYLON.ReflectionProbe = ReflectionProbe;
  99067. })(BABYLON || (BABYLON = {}));
  99068. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99069. var BABYLON;
  99070. (function (BABYLON) {
  99071. /**
  99072. * Defines the layer scene component responsible to manage any layers
  99073. * in a given scene.
  99074. */
  99075. var LayerSceneComponent = /** @class */ (function () {
  99076. /**
  99077. * Creates a new instance of the component for the given scene
  99078. * @param scene Defines the scene to register the component in
  99079. */
  99080. function LayerSceneComponent(scene) {
  99081. /**
  99082. * The component name helpfull to identify the component in the list of scene components.
  99083. */
  99084. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99085. this.scene = scene;
  99086. this._engine = scene.getEngine();
  99087. this._layers = scene.layers = new Array();
  99088. }
  99089. /**
  99090. * Registers the component in a given scene
  99091. */
  99092. LayerSceneComponent.prototype.register = function () {
  99093. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99094. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99095. };
  99096. /**
  99097. * Rebuilds the elements related to this component in case of
  99098. * context lost for instance.
  99099. */
  99100. LayerSceneComponent.prototype.rebuild = function () {
  99101. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  99102. var layer = _a[_i];
  99103. layer._rebuild();
  99104. }
  99105. };
  99106. /**
  99107. * Serializes the component data to the specified json object
  99108. * @param serializationObject The object to serialize to
  99109. */
  99110. LayerSceneComponent.prototype.serialize = function (serializationObject) {
  99111. // TODO. Implement layer serialization
  99112. // serializationObject.layers = [];
  99113. // for (let layer of this._layers) {
  99114. // if (layer.serialize) {
  99115. // serializationObject.layers.push(layer.serialize());
  99116. // }
  99117. // }
  99118. };
  99119. /**
  99120. * Adds all the element from the container to the scene
  99121. * @param container the container holding the elements
  99122. */
  99123. LayerSceneComponent.prototype.addFromContainer = function (container) {
  99124. if (!container.layers) {
  99125. return;
  99126. }
  99127. // container.layers.forEach((o) => {
  99128. // this.scene.addLayer(o);
  99129. // });
  99130. };
  99131. /**
  99132. * Removes all the elements in the container from the scene
  99133. * @param container contains the elements to remove
  99134. */
  99135. LayerSceneComponent.prototype.removeFromContainer = function (container) {
  99136. if (!container.layers) {
  99137. return;
  99138. }
  99139. // container.layers.forEach((o) => {
  99140. // this.scene.removeLayer(o);
  99141. // });
  99142. };
  99143. /**
  99144. * Disposes the component and the associated ressources.
  99145. */
  99146. LayerSceneComponent.prototype.dispose = function () {
  99147. while (this._layers.length) {
  99148. this._layers[0].dispose();
  99149. }
  99150. };
  99151. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99152. if (this._layers.length) {
  99153. this._engine.setDepthBuffer(false);
  99154. var cameraLayerMask = camera.layerMask;
  99155. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  99156. var layer = _a[_i];
  99157. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99158. layer.render();
  99159. }
  99160. }
  99161. this._engine.setDepthBuffer(true);
  99162. }
  99163. };
  99164. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99165. this._draw(camera, true);
  99166. };
  99167. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99168. this._draw(camera, false);
  99169. };
  99170. return LayerSceneComponent;
  99171. }());
  99172. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99173. })(BABYLON || (BABYLON = {}));
  99174. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99175. var BABYLON;
  99176. (function (BABYLON) {
  99177. var Layer = /** @class */ (function () {
  99178. function Layer(name, imgUrl, scene, isBackground, color) {
  99179. this.name = name;
  99180. this.scale = new BABYLON.Vector2(1, 1);
  99181. this.offset = new BABYLON.Vector2(0, 0);
  99182. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99183. this.layerMask = 0x0FFFFFFF;
  99184. this._vertexBuffers = {};
  99185. // Events
  99186. /**
  99187. * An event triggered when the layer is disposed.
  99188. */
  99189. this.onDisposeObservable = new BABYLON.Observable();
  99190. /**
  99191. * An event triggered before rendering the scene
  99192. */
  99193. this.onBeforeRenderObservable = new BABYLON.Observable();
  99194. /**
  99195. * An event triggered after rendering the scene
  99196. */
  99197. this.onAfterRenderObservable = new BABYLON.Observable();
  99198. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99199. this.isBackground = isBackground === undefined ? true : isBackground;
  99200. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99201. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99202. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99203. if (!layerComponent) {
  99204. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99205. this._scene._addComponent(layerComponent);
  99206. }
  99207. this._scene.layers.push(this);
  99208. var engine = this._scene.getEngine();
  99209. // VBO
  99210. var vertices = [];
  99211. vertices.push(1, 1);
  99212. vertices.push(-1, 1);
  99213. vertices.push(-1, -1);
  99214. vertices.push(1, -1);
  99215. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99216. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99217. this._createIndexBuffer();
  99218. // Effects
  99219. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99220. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99221. }
  99222. Object.defineProperty(Layer.prototype, "onDispose", {
  99223. set: function (callback) {
  99224. if (this._onDisposeObserver) {
  99225. this.onDisposeObservable.remove(this._onDisposeObserver);
  99226. }
  99227. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99228. },
  99229. enumerable: true,
  99230. configurable: true
  99231. });
  99232. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99233. set: function (callback) {
  99234. if (this._onBeforeRenderObserver) {
  99235. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99236. }
  99237. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99238. },
  99239. enumerable: true,
  99240. configurable: true
  99241. });
  99242. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99243. set: function (callback) {
  99244. if (this._onAfterRenderObserver) {
  99245. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99246. }
  99247. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99248. },
  99249. enumerable: true,
  99250. configurable: true
  99251. });
  99252. Layer.prototype._createIndexBuffer = function () {
  99253. var engine = this._scene.getEngine();
  99254. // Indices
  99255. var indices = [];
  99256. indices.push(0);
  99257. indices.push(1);
  99258. indices.push(2);
  99259. indices.push(0);
  99260. indices.push(2);
  99261. indices.push(3);
  99262. this._indexBuffer = engine.createIndexBuffer(indices);
  99263. };
  99264. Layer.prototype._rebuild = function () {
  99265. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99266. if (vb) {
  99267. vb._rebuild();
  99268. }
  99269. this._createIndexBuffer();
  99270. };
  99271. Layer.prototype.render = function () {
  99272. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99273. // Check
  99274. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99275. return;
  99276. var engine = this._scene.getEngine();
  99277. this.onBeforeRenderObservable.notifyObservers(this);
  99278. // Render
  99279. engine.enableEffect(currentEffect);
  99280. engine.setState(false);
  99281. // Texture
  99282. currentEffect.setTexture("textureSampler", this.texture);
  99283. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99284. // Color
  99285. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99286. // Scale / offset
  99287. currentEffect.setVector2("offset", this.offset);
  99288. currentEffect.setVector2("scale", this.scale);
  99289. // VBOs
  99290. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99291. // Draw order
  99292. if (!this.alphaTest) {
  99293. engine.setAlphaMode(this.alphaBlendingMode);
  99294. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99295. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99296. }
  99297. else {
  99298. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99299. }
  99300. this.onAfterRenderObservable.notifyObservers(this);
  99301. };
  99302. Layer.prototype.dispose = function () {
  99303. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99304. if (vertexBuffer) {
  99305. vertexBuffer.dispose();
  99306. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99307. }
  99308. if (this._indexBuffer) {
  99309. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99310. this._indexBuffer = null;
  99311. }
  99312. if (this.texture) {
  99313. this.texture.dispose();
  99314. this.texture = null;
  99315. }
  99316. // Remove from scene
  99317. var index = this._scene.layers.indexOf(this);
  99318. this._scene.layers.splice(index, 1);
  99319. // Callback
  99320. this.onDisposeObservable.notifyObservers(this);
  99321. this.onDisposeObservable.clear();
  99322. this.onAfterRenderObservable.clear();
  99323. this.onBeforeRenderObservable.clear();
  99324. };
  99325. return Layer;
  99326. }());
  99327. BABYLON.Layer = Layer;
  99328. })(BABYLON || (BABYLON = {}));
  99329. //# sourceMappingURL=babylon.layer.js.map
  99330. var BABYLON;
  99331. (function (BABYLON) {
  99332. var TextureTools = /** @class */ (function () {
  99333. function TextureTools() {
  99334. }
  99335. /**
  99336. * Uses the GPU to create a copy texture rescaled at a given size
  99337. * @param texture Texture to copy from
  99338. * @param width Desired width
  99339. * @param height Desired height
  99340. * @return Generated texture
  99341. */
  99342. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99343. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99344. var scene = texture.getScene();
  99345. var engine = scene.getEngine();
  99346. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99347. rtt.wrapU = texture.wrapU;
  99348. rtt.wrapV = texture.wrapV;
  99349. rtt.uOffset = texture.uOffset;
  99350. rtt.vOffset = texture.vOffset;
  99351. rtt.uScale = texture.uScale;
  99352. rtt.vScale = texture.vScale;
  99353. rtt.uAng = texture.uAng;
  99354. rtt.vAng = texture.vAng;
  99355. rtt.wAng = texture.wAng;
  99356. rtt.coordinatesIndex = texture.coordinatesIndex;
  99357. rtt.level = texture.level;
  99358. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99359. rtt._texture.isReady = false;
  99360. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99361. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99362. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99363. passPostProcess.getEffect().executeWhenCompiled(function () {
  99364. passPostProcess.onApply = function (effect) {
  99365. effect.setTexture("textureSampler", texture);
  99366. };
  99367. var internalTexture = rtt.getInternalTexture();
  99368. if (internalTexture) {
  99369. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99370. engine.unBindFramebuffer(internalTexture);
  99371. rtt.disposeFramebufferObjects();
  99372. passPostProcess.dispose();
  99373. internalTexture.isReady = true;
  99374. }
  99375. });
  99376. return rtt;
  99377. };
  99378. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99379. if (!scene._environmentBRDFTexture) {
  99380. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99381. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99382. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99383. scene._environmentBRDFTexture = texture;
  99384. }
  99385. return scene._environmentBRDFTexture;
  99386. };
  99387. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  99388. return TextureTools;
  99389. }());
  99390. BABYLON.TextureTools = TextureTools;
  99391. })(BABYLON || (BABYLON = {}));
  99392. //# sourceMappingURL=babylon.textureTools.js.map
  99393. var BABYLON;
  99394. (function (BABYLON) {
  99395. var FramingBehavior = /** @class */ (function () {
  99396. function FramingBehavior() {
  99397. this._mode = FramingBehavior.FitFrustumSidesMode;
  99398. this._radiusScale = 1.0;
  99399. this._positionScale = 0.5;
  99400. this._defaultElevation = 0.3;
  99401. this._elevationReturnTime = 1500;
  99402. this._elevationReturnWaitTime = 1000;
  99403. this._zoomStopsAnimation = false;
  99404. this._framingTime = 1500;
  99405. this._isPointerDown = false;
  99406. this._lastInteractionTime = -Infinity;
  99407. // Framing control
  99408. this._animatables = new Array();
  99409. this._betaIsAnimating = false;
  99410. }
  99411. Object.defineProperty(FramingBehavior.prototype, "name", {
  99412. get: function () {
  99413. return "Framing";
  99414. },
  99415. enumerable: true,
  99416. configurable: true
  99417. });
  99418. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99419. /**
  99420. * Gets current mode used by the behavior.
  99421. */
  99422. get: function () {
  99423. return this._mode;
  99424. },
  99425. /**
  99426. * Sets the current mode used by the behavior
  99427. */
  99428. set: function (mode) {
  99429. this._mode = mode;
  99430. },
  99431. enumerable: true,
  99432. configurable: true
  99433. });
  99434. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99435. /**
  99436. * Gets the scale applied to the radius
  99437. */
  99438. get: function () {
  99439. return this._radiusScale;
  99440. },
  99441. /**
  99442. * Sets the scale applied to the radius (1 by default)
  99443. */
  99444. set: function (radius) {
  99445. this._radiusScale = radius;
  99446. },
  99447. enumerable: true,
  99448. configurable: true
  99449. });
  99450. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99451. /**
  99452. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99453. */
  99454. get: function () {
  99455. return this._positionScale;
  99456. },
  99457. /**
  99458. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99459. */
  99460. set: function (scale) {
  99461. this._positionScale = scale;
  99462. },
  99463. enumerable: true,
  99464. configurable: true
  99465. });
  99466. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99467. /**
  99468. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99469. * behaviour is triggered, in radians.
  99470. */
  99471. get: function () {
  99472. return this._defaultElevation;
  99473. },
  99474. /**
  99475. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99476. * behaviour is triggered, in radians.
  99477. */
  99478. set: function (elevation) {
  99479. this._defaultElevation = elevation;
  99480. },
  99481. enumerable: true,
  99482. configurable: true
  99483. });
  99484. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99485. /**
  99486. * Gets the time (in milliseconds) taken to return to the default beta position.
  99487. * Negative value indicates camera should not return to default.
  99488. */
  99489. get: function () {
  99490. return this._elevationReturnTime;
  99491. },
  99492. /**
  99493. * Sets the time (in milliseconds) taken to return to the default beta position.
  99494. * Negative value indicates camera should not return to default.
  99495. */
  99496. set: function (speed) {
  99497. this._elevationReturnTime = speed;
  99498. },
  99499. enumerable: true,
  99500. configurable: true
  99501. });
  99502. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99503. /**
  99504. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99505. */
  99506. get: function () {
  99507. return this._elevationReturnWaitTime;
  99508. },
  99509. /**
  99510. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99511. */
  99512. set: function (time) {
  99513. this._elevationReturnWaitTime = time;
  99514. },
  99515. enumerable: true,
  99516. configurable: true
  99517. });
  99518. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99519. /**
  99520. * Gets the flag that indicates if user zooming should stop animation.
  99521. */
  99522. get: function () {
  99523. return this._zoomStopsAnimation;
  99524. },
  99525. /**
  99526. * Sets the flag that indicates if user zooming should stop animation.
  99527. */
  99528. set: function (flag) {
  99529. this._zoomStopsAnimation = flag;
  99530. },
  99531. enumerable: true,
  99532. configurable: true
  99533. });
  99534. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99535. /**
  99536. * Gets the transition time when framing the mesh, in milliseconds
  99537. */
  99538. get: function () {
  99539. return this._framingTime;
  99540. },
  99541. /**
  99542. * Sets the transition time when framing the mesh, in milliseconds
  99543. */
  99544. set: function (time) {
  99545. this._framingTime = time;
  99546. },
  99547. enumerable: true,
  99548. configurable: true
  99549. });
  99550. FramingBehavior.prototype.init = function () {
  99551. // Do notihng
  99552. };
  99553. FramingBehavior.prototype.attach = function (camera) {
  99554. var _this = this;
  99555. this._attachedCamera = camera;
  99556. var scene = this._attachedCamera.getScene();
  99557. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99558. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99559. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99560. _this._isPointerDown = true;
  99561. return;
  99562. }
  99563. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99564. _this._isPointerDown = false;
  99565. }
  99566. });
  99567. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99568. if (mesh) {
  99569. _this.zoomOnMesh(mesh);
  99570. }
  99571. });
  99572. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99573. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99574. _this._applyUserInteraction();
  99575. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99576. // back to the default position after a given timeout
  99577. _this._maintainCameraAboveGround();
  99578. });
  99579. };
  99580. FramingBehavior.prototype.detach = function () {
  99581. if (!this._attachedCamera) {
  99582. return;
  99583. }
  99584. var scene = this._attachedCamera.getScene();
  99585. if (this._onPrePointerObservableObserver) {
  99586. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99587. }
  99588. if (this._onAfterCheckInputsObserver) {
  99589. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99590. }
  99591. if (this._onMeshTargetChangedObserver) {
  99592. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99593. }
  99594. this._attachedCamera = null;
  99595. };
  99596. /**
  99597. * Targets the given mesh and updates zoom level accordingly.
  99598. * @param mesh The mesh to target.
  99599. * @param radius Optional. If a cached radius position already exists, overrides default.
  99600. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99601. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99602. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99603. */
  99604. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99605. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99606. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99607. mesh.computeWorldMatrix(true);
  99608. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99609. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99610. };
  99611. /**
  99612. * Targets the given mesh with its children and updates zoom level accordingly.
  99613. * @param mesh The mesh to target.
  99614. * @param radius Optional. If a cached radius position already exists, overrides default.
  99615. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99616. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99617. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99618. */
  99619. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99620. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99621. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99622. mesh.computeWorldMatrix(true);
  99623. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99624. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99625. };
  99626. /**
  99627. * Targets the given meshes with their children and updates zoom level accordingly.
  99628. * @param meshes The mesh to target.
  99629. * @param radius Optional. If a cached radius position already exists, overrides default.
  99630. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99631. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99632. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99633. */
  99634. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99635. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99636. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99637. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99638. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99639. for (var i = 0; i < meshes.length; i++) {
  99640. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99641. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99642. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99643. }
  99644. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99645. };
  99646. /**
  99647. * Targets the given mesh and updates zoom level accordingly.
  99648. * @param mesh The mesh to target.
  99649. * @param radius Optional. If a cached radius position already exists, overrides default.
  99650. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99651. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99652. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99653. */
  99654. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99655. var _this = this;
  99656. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99657. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99658. var zoomTarget;
  99659. if (!this._attachedCamera) {
  99660. return;
  99661. }
  99662. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99663. var bottom = minimumWorld.y;
  99664. var top = maximumWorld.y;
  99665. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99666. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99667. if (focusOnOriginXZ) {
  99668. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99669. }
  99670. else {
  99671. var centerWorld = minimumWorld.add(radiusWorld);
  99672. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99673. }
  99674. if (!this._vectorTransition) {
  99675. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99676. }
  99677. this._betaIsAnimating = true;
  99678. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99679. if (animatable) {
  99680. this._animatables.push(animatable);
  99681. }
  99682. // sets the radius and lower radius bounds
  99683. // Small delta ensures camera is not always at lower zoom limit.
  99684. var radius = 0;
  99685. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99686. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99687. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99688. radius = position;
  99689. }
  99690. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99691. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99692. if (this._attachedCamera.lowerRadiusLimit === null) {
  99693. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99694. }
  99695. }
  99696. // Set sensibilities
  99697. var extend = maximumWorld.subtract(minimumWorld).length();
  99698. this._attachedCamera.panningSensibility = 5000 / extend;
  99699. this._attachedCamera.wheelPrecision = 100 / radius;
  99700. // transition to new radius
  99701. if (!this._radiusTransition) {
  99702. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99703. }
  99704. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99705. _this.stopAllAnimations();
  99706. if (onAnimationEnd) {
  99707. onAnimationEnd();
  99708. }
  99709. if (_this._attachedCamera) {
  99710. _this._attachedCamera.storeState();
  99711. }
  99712. });
  99713. if (animatable) {
  99714. this._animatables.push(animatable);
  99715. }
  99716. };
  99717. /**
  99718. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99719. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99720. * frustum width.
  99721. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99722. * to fully enclose the mesh in the viewing frustum.
  99723. */
  99724. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99725. var size = maximumWorld.subtract(minimumWorld);
  99726. var boxVectorGlobalDiagonal = size.length();
  99727. var frustumSlope = this._getFrustumSlope();
  99728. // Formula for setting distance
  99729. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99730. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99731. // Horizon distance
  99732. var radius = radiusWithoutFraming * this._radiusScale;
  99733. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99734. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99735. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99736. var camera = this._attachedCamera;
  99737. if (!camera) {
  99738. return 0;
  99739. }
  99740. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99741. // Don't exceed the requested limit
  99742. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99743. }
  99744. // Don't exceed the upper radius limit
  99745. if (camera.upperRadiusLimit) {
  99746. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99747. }
  99748. return distance;
  99749. };
  99750. /**
  99751. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99752. * is automatically returned to its default position (expected to be above ground plane).
  99753. */
  99754. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99755. var _this = this;
  99756. if (this._elevationReturnTime < 0) {
  99757. return;
  99758. }
  99759. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99760. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99761. var limitBeta = Math.PI * 0.5;
  99762. // Bring the camera back up if below the ground plane
  99763. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99764. this._betaIsAnimating = true;
  99765. //Transition to new position
  99766. this.stopAllAnimations();
  99767. if (!this._betaTransition) {
  99768. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99769. }
  99770. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99771. _this._clearAnimationLocks();
  99772. _this.stopAllAnimations();
  99773. });
  99774. if (animatabe) {
  99775. this._animatables.push(animatabe);
  99776. }
  99777. }
  99778. };
  99779. /**
  99780. * Returns the frustum slope based on the canvas ratio and camera FOV
  99781. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99782. */
  99783. FramingBehavior.prototype._getFrustumSlope = function () {
  99784. // Calculate the viewport ratio
  99785. // Aspect Ratio is Height/Width.
  99786. var camera = this._attachedCamera;
  99787. if (!camera) {
  99788. return BABYLON.Vector2.Zero();
  99789. }
  99790. var engine = camera.getScene().getEngine();
  99791. var aspectRatio = engine.getAspectRatio(camera);
  99792. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99793. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99794. var frustumSlopeY = Math.tan(camera.fov / 2);
  99795. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99796. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99797. // along the forward vector.
  99798. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99799. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99800. };
  99801. /**
  99802. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99803. */
  99804. FramingBehavior.prototype._clearAnimationLocks = function () {
  99805. this._betaIsAnimating = false;
  99806. };
  99807. /**
  99808. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99809. */
  99810. FramingBehavior.prototype._applyUserInteraction = function () {
  99811. if (this.isUserIsMoving) {
  99812. this._lastInteractionTime = BABYLON.Tools.Now;
  99813. this.stopAllAnimations();
  99814. this._clearAnimationLocks();
  99815. }
  99816. };
  99817. /**
  99818. * Stops and removes all animations that have been applied to the camera
  99819. */
  99820. FramingBehavior.prototype.stopAllAnimations = function () {
  99821. if (this._attachedCamera) {
  99822. this._attachedCamera.animations = [];
  99823. }
  99824. while (this._animatables.length) {
  99825. if (this._animatables[0]) {
  99826. this._animatables[0].onAnimationEnd = null;
  99827. this._animatables[0].stop();
  99828. }
  99829. this._animatables.shift();
  99830. }
  99831. };
  99832. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99833. /**
  99834. * Gets a value indicating if the user is moving the camera
  99835. */
  99836. get: function () {
  99837. if (!this._attachedCamera) {
  99838. return false;
  99839. }
  99840. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99841. this._attachedCamera.inertialBetaOffset !== 0 ||
  99842. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99843. this._attachedCamera.inertialPanningX !== 0 ||
  99844. this._attachedCamera.inertialPanningY !== 0 ||
  99845. this._isPointerDown;
  99846. },
  99847. enumerable: true,
  99848. configurable: true
  99849. });
  99850. /**
  99851. * The easing function used by animations
  99852. */
  99853. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99854. /**
  99855. * The easing mode used by animations
  99856. */
  99857. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99858. // Statics
  99859. /**
  99860. * The camera can move all the way towards the mesh.
  99861. */
  99862. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99863. /**
  99864. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99865. */
  99866. FramingBehavior.FitFrustumSidesMode = 1;
  99867. return FramingBehavior;
  99868. }());
  99869. BABYLON.FramingBehavior = FramingBehavior;
  99870. })(BABYLON || (BABYLON = {}));
  99871. //# sourceMappingURL=babylon.framingBehavior.js.map
  99872. var BABYLON;
  99873. (function (BABYLON) {
  99874. /**
  99875. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99876. */
  99877. var BouncingBehavior = /** @class */ (function () {
  99878. function BouncingBehavior() {
  99879. /**
  99880. * The duration of the animation, in milliseconds
  99881. */
  99882. this.transitionDuration = 450;
  99883. /**
  99884. * Length of the distance animated by the transition when lower radius is reached
  99885. */
  99886. this.lowerRadiusTransitionRange = 2;
  99887. /**
  99888. * Length of the distance animated by the transition when upper radius is reached
  99889. */
  99890. this.upperRadiusTransitionRange = -2;
  99891. this._autoTransitionRange = false;
  99892. // Animations
  99893. this._radiusIsAnimating = false;
  99894. this._radiusBounceTransition = null;
  99895. this._animatables = new Array();
  99896. }
  99897. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99898. get: function () {
  99899. return "Bouncing";
  99900. },
  99901. enumerable: true,
  99902. configurable: true
  99903. });
  99904. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99905. /**
  99906. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99907. */
  99908. get: function () {
  99909. return this._autoTransitionRange;
  99910. },
  99911. /**
  99912. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99913. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99914. */
  99915. set: function (value) {
  99916. var _this = this;
  99917. if (this._autoTransitionRange === value) {
  99918. return;
  99919. }
  99920. this._autoTransitionRange = value;
  99921. var camera = this._attachedCamera;
  99922. if (!camera) {
  99923. return;
  99924. }
  99925. if (value) {
  99926. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99927. if (!mesh) {
  99928. return;
  99929. }
  99930. mesh.computeWorldMatrix(true);
  99931. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99932. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99933. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99934. });
  99935. }
  99936. else if (this._onMeshTargetChangedObserver) {
  99937. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99938. }
  99939. },
  99940. enumerable: true,
  99941. configurable: true
  99942. });
  99943. BouncingBehavior.prototype.init = function () {
  99944. // Do notihng
  99945. };
  99946. BouncingBehavior.prototype.attach = function (camera) {
  99947. var _this = this;
  99948. this._attachedCamera = camera;
  99949. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99950. if (!_this._attachedCamera) {
  99951. return;
  99952. }
  99953. // Add the bounce animation to the lower radius limit
  99954. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99955. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99956. }
  99957. // Add the bounce animation to the upper radius limit
  99958. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99959. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99960. }
  99961. });
  99962. };
  99963. BouncingBehavior.prototype.detach = function () {
  99964. if (!this._attachedCamera) {
  99965. return;
  99966. }
  99967. if (this._onAfterCheckInputsObserver) {
  99968. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99969. }
  99970. if (this._onMeshTargetChangedObserver) {
  99971. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99972. }
  99973. this._attachedCamera = null;
  99974. };
  99975. /**
  99976. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  99977. * @param radiusLimit The limit to check against.
  99978. * @return Bool to indicate if at limit.
  99979. */
  99980. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  99981. if (!this._attachedCamera) {
  99982. return false;
  99983. }
  99984. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  99985. return true;
  99986. }
  99987. return false;
  99988. };
  99989. /**
  99990. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  99991. * @param radiusDelta The delta by which to animate to. Can be negative.
  99992. */
  99993. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  99994. var _this = this;
  99995. if (!this._attachedCamera) {
  99996. return;
  99997. }
  99998. if (!this._radiusBounceTransition) {
  99999. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100000. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100001. }
  100002. // Prevent zoom until bounce has completed
  100003. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100004. this._attachedCamera.wheelPrecision = Infinity;
  100005. this._attachedCamera.inertialRadiusOffset = 0;
  100006. // Animate to the radius limit
  100007. this.stopAllAnimations();
  100008. this._radiusIsAnimating = true;
  100009. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100010. if (animatable) {
  100011. this._animatables.push(animatable);
  100012. }
  100013. };
  100014. /**
  100015. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100016. */
  100017. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100018. this._radiusIsAnimating = false;
  100019. if (this._attachedCamera) {
  100020. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100021. }
  100022. };
  100023. /**
  100024. * Stops and removes all animations that have been applied to the camera
  100025. */
  100026. BouncingBehavior.prototype.stopAllAnimations = function () {
  100027. if (this._attachedCamera) {
  100028. this._attachedCamera.animations = [];
  100029. }
  100030. while (this._animatables.length) {
  100031. this._animatables[0].onAnimationEnd = null;
  100032. this._animatables[0].stop();
  100033. this._animatables.shift();
  100034. }
  100035. };
  100036. /**
  100037. * The easing function used by animations
  100038. */
  100039. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100040. /**
  100041. * The easing mode used by animations
  100042. */
  100043. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100044. return BouncingBehavior;
  100045. }());
  100046. BABYLON.BouncingBehavior = BouncingBehavior;
  100047. })(BABYLON || (BABYLON = {}));
  100048. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100049. var BABYLON;
  100050. (function (BABYLON) {
  100051. var AutoRotationBehavior = /** @class */ (function () {
  100052. function AutoRotationBehavior() {
  100053. this._zoomStopsAnimation = false;
  100054. this._idleRotationSpeed = 0.05;
  100055. this._idleRotationWaitTime = 2000;
  100056. this._idleRotationSpinupTime = 2000;
  100057. this._isPointerDown = false;
  100058. this._lastFrameTime = null;
  100059. this._lastInteractionTime = -Infinity;
  100060. this._cameraRotationSpeed = 0;
  100061. this._lastFrameRadius = 0;
  100062. }
  100063. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100064. get: function () {
  100065. return "AutoRotation";
  100066. },
  100067. enumerable: true,
  100068. configurable: true
  100069. });
  100070. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100071. /**
  100072. * Gets the flag that indicates if user zooming should stop animation.
  100073. */
  100074. get: function () {
  100075. return this._zoomStopsAnimation;
  100076. },
  100077. /**
  100078. * Sets the flag that indicates if user zooming should stop animation.
  100079. */
  100080. set: function (flag) {
  100081. this._zoomStopsAnimation = flag;
  100082. },
  100083. enumerable: true,
  100084. configurable: true
  100085. });
  100086. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100087. /**
  100088. * Gets the default speed at which the camera rotates around the model.
  100089. */
  100090. get: function () {
  100091. return this._idleRotationSpeed;
  100092. },
  100093. /**
  100094. * Sets the default speed at which the camera rotates around the model.
  100095. */
  100096. set: function (speed) {
  100097. this._idleRotationSpeed = speed;
  100098. },
  100099. enumerable: true,
  100100. configurable: true
  100101. });
  100102. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100103. /**
  100104. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100105. */
  100106. get: function () {
  100107. return this._idleRotationWaitTime;
  100108. },
  100109. /**
  100110. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100111. */
  100112. set: function (time) {
  100113. this._idleRotationWaitTime = time;
  100114. },
  100115. enumerable: true,
  100116. configurable: true
  100117. });
  100118. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100119. /**
  100120. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100121. */
  100122. get: function () {
  100123. return this._idleRotationSpinupTime;
  100124. },
  100125. /**
  100126. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100127. */
  100128. set: function (time) {
  100129. this._idleRotationSpinupTime = time;
  100130. },
  100131. enumerable: true,
  100132. configurable: true
  100133. });
  100134. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100135. /**
  100136. * Gets a value indicating if the camera is currently rotating because of this behavior
  100137. */
  100138. get: function () {
  100139. return Math.abs(this._cameraRotationSpeed) > 0;
  100140. },
  100141. enumerable: true,
  100142. configurable: true
  100143. });
  100144. AutoRotationBehavior.prototype.init = function () {
  100145. // Do notihng
  100146. };
  100147. AutoRotationBehavior.prototype.attach = function (camera) {
  100148. var _this = this;
  100149. this._attachedCamera = camera;
  100150. var scene = this._attachedCamera.getScene();
  100151. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100152. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100153. _this._isPointerDown = true;
  100154. return;
  100155. }
  100156. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100157. _this._isPointerDown = false;
  100158. }
  100159. });
  100160. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100161. var now = BABYLON.Tools.Now;
  100162. var dt = 0;
  100163. if (_this._lastFrameTime != null) {
  100164. dt = now - _this._lastFrameTime;
  100165. }
  100166. _this._lastFrameTime = now;
  100167. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100168. _this._applyUserInteraction();
  100169. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100170. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100171. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100172. // Step camera rotation by rotation speed
  100173. if (_this._attachedCamera) {
  100174. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100175. }
  100176. });
  100177. };
  100178. AutoRotationBehavior.prototype.detach = function () {
  100179. if (!this._attachedCamera) {
  100180. return;
  100181. }
  100182. var scene = this._attachedCamera.getScene();
  100183. if (this._onPrePointerObservableObserver) {
  100184. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100185. }
  100186. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100187. this._attachedCamera = null;
  100188. };
  100189. /**
  100190. * Returns true if user is scrolling.
  100191. * @return true if user is scrolling.
  100192. */
  100193. AutoRotationBehavior.prototype._userIsZooming = function () {
  100194. if (!this._attachedCamera) {
  100195. return false;
  100196. }
  100197. return this._attachedCamera.inertialRadiusOffset !== 0;
  100198. };
  100199. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100200. if (!this._attachedCamera) {
  100201. return false;
  100202. }
  100203. var zoomHasHitLimit = false;
  100204. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100205. zoomHasHitLimit = true;
  100206. }
  100207. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100208. this._lastFrameRadius = this._attachedCamera.radius;
  100209. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100210. };
  100211. /**
  100212. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100213. */
  100214. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100215. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100216. this._lastInteractionTime = BABYLON.Tools.Now;
  100217. }
  100218. };
  100219. // Tools
  100220. AutoRotationBehavior.prototype._userIsMoving = function () {
  100221. if (!this._attachedCamera) {
  100222. return false;
  100223. }
  100224. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100225. this._attachedCamera.inertialBetaOffset !== 0 ||
  100226. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100227. this._attachedCamera.inertialPanningX !== 0 ||
  100228. this._attachedCamera.inertialPanningY !== 0 ||
  100229. this._isPointerDown;
  100230. };
  100231. return AutoRotationBehavior;
  100232. }());
  100233. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100234. })(BABYLON || (BABYLON = {}));
  100235. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100236. var BABYLON;
  100237. (function (BABYLON) {
  100238. var NullEngineOptions = /** @class */ (function () {
  100239. function NullEngineOptions() {
  100240. this.renderWidth = 512;
  100241. this.renderHeight = 256;
  100242. this.textureSize = 512;
  100243. this.deterministicLockstep = false;
  100244. this.lockstepMaxSteps = 4;
  100245. }
  100246. return NullEngineOptions;
  100247. }());
  100248. BABYLON.NullEngineOptions = NullEngineOptions;
  100249. /**
  100250. * The null engine class provides support for headless version of babylon.js.
  100251. * This can be used in server side scenario or for testing purposes
  100252. */
  100253. var NullEngine = /** @class */ (function (_super) {
  100254. __extends(NullEngine, _super);
  100255. function NullEngine(options) {
  100256. if (options === void 0) { options = new NullEngineOptions(); }
  100257. var _this = _super.call(this, null) || this;
  100258. if (options.deterministicLockstep === undefined) {
  100259. options.deterministicLockstep = false;
  100260. }
  100261. if (options.lockstepMaxSteps === undefined) {
  100262. options.lockstepMaxSteps = 4;
  100263. }
  100264. _this._options = options;
  100265. // Init caps
  100266. // We consider we are on a webgl1 capable device
  100267. _this._caps = new BABYLON.EngineCapabilities();
  100268. _this._caps.maxTexturesImageUnits = 16;
  100269. _this._caps.maxVertexTextureImageUnits = 16;
  100270. _this._caps.maxTextureSize = 512;
  100271. _this._caps.maxCubemapTextureSize = 512;
  100272. _this._caps.maxRenderTextureSize = 512;
  100273. _this._caps.maxVertexAttribs = 16;
  100274. _this._caps.maxVaryingVectors = 16;
  100275. _this._caps.maxFragmentUniformVectors = 16;
  100276. _this._caps.maxVertexUniformVectors = 16;
  100277. // Extensions
  100278. _this._caps.standardDerivatives = false;
  100279. _this._caps.astc = null;
  100280. _this._caps.s3tc = null;
  100281. _this._caps.pvrtc = null;
  100282. _this._caps.etc1 = null;
  100283. _this._caps.etc2 = null;
  100284. _this._caps.textureAnisotropicFilterExtension = null;
  100285. _this._caps.maxAnisotropy = 0;
  100286. _this._caps.uintIndices = false;
  100287. _this._caps.fragmentDepthSupported = false;
  100288. _this._caps.highPrecisionShaderSupported = true;
  100289. _this._caps.colorBufferFloat = false;
  100290. _this._caps.textureFloat = false;
  100291. _this._caps.textureFloatLinearFiltering = false;
  100292. _this._caps.textureFloatRender = false;
  100293. _this._caps.textureHalfFloat = false;
  100294. _this._caps.textureHalfFloatLinearFiltering = false;
  100295. _this._caps.textureHalfFloatRender = false;
  100296. _this._caps.textureLOD = false;
  100297. _this._caps.drawBuffersExtension = false;
  100298. _this._caps.depthTextureExtension = false;
  100299. _this._caps.vertexArrayObject = false;
  100300. _this._caps.instancedArrays = false;
  100301. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100302. // Wrappers
  100303. if (typeof URL === "undefined") {
  100304. URL = {
  100305. createObjectURL: function () { },
  100306. revokeObjectURL: function () { }
  100307. };
  100308. }
  100309. if (typeof Blob === "undefined") {
  100310. Blob = function () { };
  100311. }
  100312. return _this;
  100313. }
  100314. NullEngine.prototype.isDeterministicLockStep = function () {
  100315. return this._options.deterministicLockstep;
  100316. };
  100317. NullEngine.prototype.getLockstepMaxSteps = function () {
  100318. return this._options.lockstepMaxSteps;
  100319. };
  100320. NullEngine.prototype.getHardwareScalingLevel = function () {
  100321. return 1.0;
  100322. };
  100323. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100324. return {
  100325. capacity: 0,
  100326. references: 1,
  100327. is32Bits: false
  100328. };
  100329. };
  100330. NullEngine.prototype.createIndexBuffer = function (indices) {
  100331. return {
  100332. capacity: 0,
  100333. references: 1,
  100334. is32Bits: false
  100335. };
  100336. };
  100337. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100338. if (stencil === void 0) { stencil = false; }
  100339. };
  100340. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100341. if (useScreen === void 0) { useScreen = false; }
  100342. if (!useScreen && this._currentRenderTarget) {
  100343. return this._currentRenderTarget.width;
  100344. }
  100345. return this._options.renderWidth;
  100346. };
  100347. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100348. if (useScreen === void 0) { useScreen = false; }
  100349. if (!useScreen && this._currentRenderTarget) {
  100350. return this._currentRenderTarget.height;
  100351. }
  100352. return this._options.renderHeight;
  100353. };
  100354. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100355. this._cachedViewport = viewport;
  100356. };
  100357. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100358. return {
  100359. transformFeedback: null,
  100360. __SPECTOR_rebuildProgram: null
  100361. };
  100362. };
  100363. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100364. return [];
  100365. };
  100366. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100367. return [];
  100368. };
  100369. NullEngine.prototype.bindSamplers = function (effect) {
  100370. this._currentEffect = null;
  100371. };
  100372. NullEngine.prototype.enableEffect = function (effect) {
  100373. this._currentEffect = effect;
  100374. if (effect.onBind) {
  100375. effect.onBind(effect);
  100376. }
  100377. effect.onBindObservable.notifyObservers(effect);
  100378. };
  100379. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100380. if (zOffset === void 0) { zOffset = 0; }
  100381. if (reverseSide === void 0) { reverseSide = false; }
  100382. };
  100383. NullEngine.prototype.setIntArray = function (uniform, array) {
  100384. };
  100385. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100386. };
  100387. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100388. };
  100389. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100390. };
  100391. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100392. };
  100393. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100394. };
  100395. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100396. };
  100397. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100398. };
  100399. NullEngine.prototype.setArray = function (uniform, array) {
  100400. };
  100401. NullEngine.prototype.setArray2 = function (uniform, array) {
  100402. };
  100403. NullEngine.prototype.setArray3 = function (uniform, array) {
  100404. };
  100405. NullEngine.prototype.setArray4 = function (uniform, array) {
  100406. };
  100407. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100408. };
  100409. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100410. };
  100411. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100412. };
  100413. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100414. };
  100415. NullEngine.prototype.setFloat = function (uniform, value) {
  100416. };
  100417. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100418. };
  100419. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100420. };
  100421. NullEngine.prototype.setBool = function (uniform, bool) {
  100422. };
  100423. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100424. };
  100425. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100426. };
  100427. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100428. };
  100429. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100430. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100431. if (this._alphaMode === mode) {
  100432. return;
  100433. }
  100434. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100435. if (!noDepthWriteChange) {
  100436. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100437. }
  100438. this._alphaMode = mode;
  100439. };
  100440. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100441. };
  100442. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100443. if (this.preventCacheWipeBetweenFrames) {
  100444. return;
  100445. }
  100446. this.resetTextureCache();
  100447. this._currentEffect = null;
  100448. if (bruteForce) {
  100449. this._currentProgram = null;
  100450. this._stencilState.reset();
  100451. this._depthCullingState.reset();
  100452. this._alphaState.reset();
  100453. }
  100454. this._cachedVertexBuffers = null;
  100455. this._cachedIndexBuffer = null;
  100456. this._cachedEffectForVertexBuffers = null;
  100457. };
  100458. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100459. };
  100460. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100461. };
  100462. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100463. };
  100464. NullEngine.prototype._createTexture = function () {
  100465. return {};
  100466. };
  100467. NullEngine.prototype._releaseTexture = function (texture) {
  100468. };
  100469. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100471. if (onLoad === void 0) { onLoad = null; }
  100472. if (onError === void 0) { onError = null; }
  100473. if (buffer === void 0) { buffer = null; }
  100474. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100475. var url = String(urlArg);
  100476. texture.url = url;
  100477. texture.generateMipMaps = !noMipmap;
  100478. texture.samplingMode = samplingMode;
  100479. texture.invertY = invertY;
  100480. texture.baseWidth = this._options.textureSize;
  100481. texture.baseHeight = this._options.textureSize;
  100482. texture.width = this._options.textureSize;
  100483. texture.height = this._options.textureSize;
  100484. if (format) {
  100485. texture.format = format;
  100486. }
  100487. texture.isReady = true;
  100488. if (onLoad) {
  100489. onLoad();
  100490. }
  100491. this._internalTexturesCache.push(texture);
  100492. return texture;
  100493. };
  100494. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100495. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100496. if (options !== undefined && typeof options === "object") {
  100497. fullOptions.generateMipMaps = options.generateMipMaps;
  100498. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100499. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100500. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100501. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100502. }
  100503. else {
  100504. fullOptions.generateMipMaps = options;
  100505. fullOptions.generateDepthBuffer = true;
  100506. fullOptions.generateStencilBuffer = false;
  100507. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100508. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100509. }
  100510. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100511. var width = size.width || size;
  100512. var height = size.height || size;
  100513. texture._depthStencilBuffer = {};
  100514. texture._framebuffer = {};
  100515. texture.baseWidth = width;
  100516. texture.baseHeight = height;
  100517. texture.width = width;
  100518. texture.height = height;
  100519. texture.isReady = true;
  100520. texture.samples = 1;
  100521. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100522. texture.samplingMode = fullOptions.samplingMode;
  100523. texture.type = fullOptions.type;
  100524. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100525. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100526. this._internalTexturesCache.push(texture);
  100527. return texture;
  100528. };
  100529. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100530. texture.samplingMode = samplingMode;
  100531. };
  100532. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100533. if (this._currentRenderTarget) {
  100534. this.unBindFramebuffer(this._currentRenderTarget);
  100535. }
  100536. this._currentRenderTarget = texture;
  100537. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100538. if (this._cachedViewport && !forceFullscreenViewport) {
  100539. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100540. }
  100541. };
  100542. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100543. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100544. this._currentRenderTarget = null;
  100545. if (onBeforeUnbind) {
  100546. if (texture._MSAAFramebuffer) {
  100547. this._currentFramebuffer = texture._framebuffer;
  100548. }
  100549. onBeforeUnbind();
  100550. }
  100551. this._currentFramebuffer = null;
  100552. };
  100553. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100554. var vbo = {
  100555. capacity: 1,
  100556. references: 1,
  100557. is32Bits: false
  100558. };
  100559. return vbo;
  100560. };
  100561. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100562. if (premulAlpha === void 0) { premulAlpha = false; }
  100563. };
  100564. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100565. if (offset === void 0) { offset = 0; }
  100566. };
  100567. /**
  100568. * Updates a dynamic vertex buffer.
  100569. * @param vertexBuffer the vertex buffer to update
  100570. * @param data the data used to update the vertex buffer
  100571. * @param byteOffset the byte offset of the data (optional)
  100572. * @param byteLength the byte length of the data (optional)
  100573. */
  100574. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100575. };
  100576. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100577. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100578. this._boundTexturesCache[this._activeChannel] = texture;
  100579. return true;
  100580. }
  100581. return false;
  100582. };
  100583. NullEngine.prototype._bindTexture = function (channel, texture) {
  100584. if (channel < 0) {
  100585. return;
  100586. }
  100587. this._bindTextureDirectly(0, texture);
  100588. };
  100589. NullEngine.prototype._releaseBuffer = function (buffer) {
  100590. buffer.references--;
  100591. if (buffer.references === 0) {
  100592. return true;
  100593. }
  100594. return false;
  100595. };
  100596. NullEngine.prototype.releaseEffects = function () {
  100597. };
  100598. NullEngine.prototype.displayLoadingUI = function () {
  100599. };
  100600. NullEngine.prototype.hideLoadingUI = function () {
  100601. };
  100602. return NullEngine;
  100603. }(BABYLON.Engine));
  100604. BABYLON.NullEngine = NullEngine;
  100605. })(BABYLON || (BABYLON = {}));
  100606. //# sourceMappingURL=babylon.nullEngine.js.map
  100607. var BABYLON;
  100608. (function (BABYLON) {
  100609. /**
  100610. * This class can be used to get instrumentation data from a Babylon engine
  100611. */
  100612. var EngineInstrumentation = /** @class */ (function () {
  100613. function EngineInstrumentation(engine) {
  100614. this.engine = engine;
  100615. this._captureGPUFrameTime = false;
  100616. this._gpuFrameTime = new BABYLON.PerfCounter();
  100617. this._captureShaderCompilationTime = false;
  100618. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100619. // Observers
  100620. this._onBeginFrameObserver = null;
  100621. this._onEndFrameObserver = null;
  100622. this._onBeforeShaderCompilationObserver = null;
  100623. this._onAfterShaderCompilationObserver = null;
  100624. }
  100625. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100626. // Properties
  100627. /**
  100628. * Gets the perf counter used for GPU frame time
  100629. */
  100630. get: function () {
  100631. return this._gpuFrameTime;
  100632. },
  100633. enumerable: true,
  100634. configurable: true
  100635. });
  100636. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100637. /**
  100638. * Gets the GPU frame time capture status
  100639. */
  100640. get: function () {
  100641. return this._captureGPUFrameTime;
  100642. },
  100643. /**
  100644. * Enable or disable the GPU frame time capture
  100645. */
  100646. set: function (value) {
  100647. var _this = this;
  100648. if (value === this._captureGPUFrameTime) {
  100649. return;
  100650. }
  100651. this._captureGPUFrameTime = value;
  100652. if (value) {
  100653. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100654. if (!_this._gpuFrameTimeToken) {
  100655. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100656. }
  100657. });
  100658. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100659. if (!_this._gpuFrameTimeToken) {
  100660. return;
  100661. }
  100662. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100663. if (time > -1) {
  100664. _this._gpuFrameTimeToken = null;
  100665. _this._gpuFrameTime.fetchNewFrame();
  100666. _this._gpuFrameTime.addCount(time, true);
  100667. }
  100668. });
  100669. }
  100670. else {
  100671. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100672. this._onBeginFrameObserver = null;
  100673. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100674. this._onEndFrameObserver = null;
  100675. }
  100676. },
  100677. enumerable: true,
  100678. configurable: true
  100679. });
  100680. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100681. /**
  100682. * Gets the perf counter used for shader compilation time
  100683. */
  100684. get: function () {
  100685. return this._shaderCompilationTime;
  100686. },
  100687. enumerable: true,
  100688. configurable: true
  100689. });
  100690. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100691. /**
  100692. * Gets the shader compilation time capture status
  100693. */
  100694. get: function () {
  100695. return this._captureShaderCompilationTime;
  100696. },
  100697. /**
  100698. * Enable or disable the shader compilation time capture
  100699. */
  100700. set: function (value) {
  100701. var _this = this;
  100702. if (value === this._captureShaderCompilationTime) {
  100703. return;
  100704. }
  100705. this._captureShaderCompilationTime = value;
  100706. if (value) {
  100707. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100708. _this._shaderCompilationTime.fetchNewFrame();
  100709. _this._shaderCompilationTime.beginMonitoring();
  100710. });
  100711. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100712. _this._shaderCompilationTime.endMonitoring();
  100713. });
  100714. }
  100715. else {
  100716. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100717. this._onBeforeShaderCompilationObserver = null;
  100718. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100719. this._onAfterShaderCompilationObserver = null;
  100720. }
  100721. },
  100722. enumerable: true,
  100723. configurable: true
  100724. });
  100725. EngineInstrumentation.prototype.dispose = function () {
  100726. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100727. this._onBeginFrameObserver = null;
  100728. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100729. this._onEndFrameObserver = null;
  100730. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100731. this._onBeforeShaderCompilationObserver = null;
  100732. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100733. this._onAfterShaderCompilationObserver = null;
  100734. this.engine = null;
  100735. };
  100736. return EngineInstrumentation;
  100737. }());
  100738. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100739. })(BABYLON || (BABYLON = {}));
  100740. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100741. var BABYLON;
  100742. (function (BABYLON) {
  100743. /**
  100744. * This class can be used to get instrumentation data from a Babylon engine
  100745. */
  100746. var SceneInstrumentation = /** @class */ (function () {
  100747. function SceneInstrumentation(scene) {
  100748. var _this = this;
  100749. this.scene = scene;
  100750. this._captureActiveMeshesEvaluationTime = false;
  100751. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100752. this._captureRenderTargetsRenderTime = false;
  100753. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100754. this._captureFrameTime = false;
  100755. this._frameTime = new BABYLON.PerfCounter();
  100756. this._captureRenderTime = false;
  100757. this._renderTime = new BABYLON.PerfCounter();
  100758. this._captureInterFrameTime = false;
  100759. this._interFrameTime = new BABYLON.PerfCounter();
  100760. this._captureParticlesRenderTime = false;
  100761. this._particlesRenderTime = new BABYLON.PerfCounter();
  100762. this._captureSpritesRenderTime = false;
  100763. this._spritesRenderTime = new BABYLON.PerfCounter();
  100764. this._capturePhysicsTime = false;
  100765. this._physicsTime = new BABYLON.PerfCounter();
  100766. this._captureAnimationsTime = false;
  100767. this._animationsTime = new BABYLON.PerfCounter();
  100768. this._captureCameraRenderTime = false;
  100769. this._cameraRenderTime = new BABYLON.PerfCounter();
  100770. // Observers
  100771. this._onBeforeActiveMeshesEvaluationObserver = null;
  100772. this._onAfterActiveMeshesEvaluationObserver = null;
  100773. this._onBeforeRenderTargetsRenderObserver = null;
  100774. this._onAfterRenderTargetsRenderObserver = null;
  100775. this._onAfterRenderObserver = null;
  100776. this._onBeforeDrawPhaseObserver = null;
  100777. this._onAfterDrawPhaseObserver = null;
  100778. this._onBeforeAnimationsObserver = null;
  100779. this._onBeforeParticlesRenderingObserver = null;
  100780. this._onAfterParticlesRenderingObserver = null;
  100781. this._onBeforeSpritesRenderingObserver = null;
  100782. this._onAfterSpritesRenderingObserver = null;
  100783. this._onBeforePhysicsObserver = null;
  100784. this._onAfterPhysicsObserver = null;
  100785. this._onAfterAnimationsObserver = null;
  100786. this._onBeforeCameraRenderObserver = null;
  100787. this._onAfterCameraRenderObserver = null;
  100788. // Before render
  100789. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100790. if (_this._captureActiveMeshesEvaluationTime) {
  100791. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100792. }
  100793. if (_this._captureRenderTargetsRenderTime) {
  100794. _this._renderTargetsRenderTime.fetchNewFrame();
  100795. }
  100796. if (_this._captureFrameTime) {
  100797. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100798. _this._frameTime.beginMonitoring();
  100799. }
  100800. if (_this._captureInterFrameTime) {
  100801. _this._interFrameTime.endMonitoring();
  100802. }
  100803. if (_this._captureParticlesRenderTime) {
  100804. _this._particlesRenderTime.fetchNewFrame();
  100805. }
  100806. if (_this._captureSpritesRenderTime) {
  100807. _this._spritesRenderTime.fetchNewFrame();
  100808. }
  100809. if (_this._captureAnimationsTime) {
  100810. _this._animationsTime.beginMonitoring();
  100811. }
  100812. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100813. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100814. });
  100815. // After render
  100816. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100817. if (_this._captureFrameTime) {
  100818. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100819. _this._frameTime.endMonitoring();
  100820. }
  100821. if (_this._captureRenderTime) {
  100822. _this._renderTime.endMonitoring(false);
  100823. }
  100824. if (_this._captureInterFrameTime) {
  100825. _this._interFrameTime.beginMonitoring();
  100826. }
  100827. });
  100828. }
  100829. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100830. // Properties
  100831. /**
  100832. * Gets the perf counter used for active meshes evaluation time
  100833. */
  100834. get: function () {
  100835. return this._activeMeshesEvaluationTime;
  100836. },
  100837. enumerable: true,
  100838. configurable: true
  100839. });
  100840. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100841. /**
  100842. * Gets the active meshes evaluation time capture status
  100843. */
  100844. get: function () {
  100845. return this._captureActiveMeshesEvaluationTime;
  100846. },
  100847. /**
  100848. * Enable or disable the active meshes evaluation time capture
  100849. */
  100850. set: function (value) {
  100851. var _this = this;
  100852. if (value === this._captureActiveMeshesEvaluationTime) {
  100853. return;
  100854. }
  100855. this._captureActiveMeshesEvaluationTime = value;
  100856. if (value) {
  100857. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100858. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100859. _this._activeMeshesEvaluationTime.beginMonitoring();
  100860. });
  100861. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100862. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100863. _this._activeMeshesEvaluationTime.endMonitoring();
  100864. });
  100865. }
  100866. else {
  100867. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100868. this._onBeforeActiveMeshesEvaluationObserver = null;
  100869. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100870. this._onAfterActiveMeshesEvaluationObserver = null;
  100871. }
  100872. },
  100873. enumerable: true,
  100874. configurable: true
  100875. });
  100876. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100877. /**
  100878. * Gets the perf counter used for render targets render time
  100879. */
  100880. get: function () {
  100881. return this._renderTargetsRenderTime;
  100882. },
  100883. enumerable: true,
  100884. configurable: true
  100885. });
  100886. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100887. /**
  100888. * Gets the render targets render time capture status
  100889. */
  100890. get: function () {
  100891. return this._captureRenderTargetsRenderTime;
  100892. },
  100893. /**
  100894. * Enable or disable the render targets render time capture
  100895. */
  100896. set: function (value) {
  100897. var _this = this;
  100898. if (value === this._captureRenderTargetsRenderTime) {
  100899. return;
  100900. }
  100901. this._captureRenderTargetsRenderTime = value;
  100902. if (value) {
  100903. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100904. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100905. _this._renderTargetsRenderTime.beginMonitoring();
  100906. });
  100907. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100908. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100909. _this._renderTargetsRenderTime.endMonitoring(false);
  100910. });
  100911. }
  100912. else {
  100913. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100914. this._onBeforeRenderTargetsRenderObserver = null;
  100915. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100916. this._onAfterRenderTargetsRenderObserver = null;
  100917. }
  100918. },
  100919. enumerable: true,
  100920. configurable: true
  100921. });
  100922. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100923. /**
  100924. * Gets the perf counter used for particles render time
  100925. */
  100926. get: function () {
  100927. return this._particlesRenderTime;
  100928. },
  100929. enumerable: true,
  100930. configurable: true
  100931. });
  100932. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100933. /**
  100934. * Gets the particles render time capture status
  100935. */
  100936. get: function () {
  100937. return this._captureParticlesRenderTime;
  100938. },
  100939. /**
  100940. * Enable or disable the particles render time capture
  100941. */
  100942. set: function (value) {
  100943. var _this = this;
  100944. if (value === this._captureParticlesRenderTime) {
  100945. return;
  100946. }
  100947. this._captureParticlesRenderTime = value;
  100948. if (value) {
  100949. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  100950. BABYLON.Tools.StartPerformanceCounter("Particles");
  100951. _this._particlesRenderTime.beginMonitoring();
  100952. });
  100953. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  100954. BABYLON.Tools.EndPerformanceCounter("Particles");
  100955. _this._particlesRenderTime.endMonitoring(false);
  100956. });
  100957. }
  100958. else {
  100959. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100960. this._onBeforeParticlesRenderingObserver = null;
  100961. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100962. this._onAfterParticlesRenderingObserver = null;
  100963. }
  100964. },
  100965. enumerable: true,
  100966. configurable: true
  100967. });
  100968. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  100969. /**
  100970. * Gets the perf counter used for sprites render time
  100971. */
  100972. get: function () {
  100973. return this._spritesRenderTime;
  100974. },
  100975. enumerable: true,
  100976. configurable: true
  100977. });
  100978. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  100979. /**
  100980. * Gets the sprites render time capture status
  100981. */
  100982. get: function () {
  100983. return this._captureSpritesRenderTime;
  100984. },
  100985. /**
  100986. * Enable or disable the sprites render time capture
  100987. */
  100988. set: function (value) {
  100989. var _this = this;
  100990. if (value === this._captureSpritesRenderTime) {
  100991. return;
  100992. }
  100993. this._captureSpritesRenderTime = value;
  100994. if (value) {
  100995. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  100996. BABYLON.Tools.StartPerformanceCounter("Sprites");
  100997. _this._spritesRenderTime.beginMonitoring();
  100998. });
  100999. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101000. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101001. _this._spritesRenderTime.endMonitoring(false);
  101002. });
  101003. }
  101004. else {
  101005. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101006. this._onBeforeSpritesRenderingObserver = null;
  101007. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101008. this._onAfterSpritesRenderingObserver = null;
  101009. }
  101010. },
  101011. enumerable: true,
  101012. configurable: true
  101013. });
  101014. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101015. /**
  101016. * Gets the perf counter used for physics time
  101017. */
  101018. get: function () {
  101019. return this._physicsTime;
  101020. },
  101021. enumerable: true,
  101022. configurable: true
  101023. });
  101024. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101025. /**
  101026. * Gets the physics time capture status
  101027. */
  101028. get: function () {
  101029. return this._capturePhysicsTime;
  101030. },
  101031. /**
  101032. * Enable or disable the physics time capture
  101033. */
  101034. set: function (value) {
  101035. var _this = this;
  101036. if (value === this._capturePhysicsTime) {
  101037. return;
  101038. }
  101039. this._capturePhysicsTime = value;
  101040. if (value) {
  101041. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101042. BABYLON.Tools.StartPerformanceCounter("Physics");
  101043. _this._physicsTime.beginMonitoring();
  101044. });
  101045. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101046. BABYLON.Tools.EndPerformanceCounter("Physics");
  101047. _this._physicsTime.endMonitoring();
  101048. });
  101049. }
  101050. else {
  101051. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101052. this._onBeforePhysicsObserver = null;
  101053. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101054. this._onAfterPhysicsObserver = null;
  101055. }
  101056. },
  101057. enumerable: true,
  101058. configurable: true
  101059. });
  101060. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101061. /**
  101062. * Gets the perf counter used for animations time
  101063. */
  101064. get: function () {
  101065. return this._animationsTime;
  101066. },
  101067. enumerable: true,
  101068. configurable: true
  101069. });
  101070. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101071. /**
  101072. * Gets the animations time capture status
  101073. */
  101074. get: function () {
  101075. return this._captureAnimationsTime;
  101076. },
  101077. /**
  101078. * Enable or disable the animations time capture
  101079. */
  101080. set: function (value) {
  101081. var _this = this;
  101082. if (value === this._captureAnimationsTime) {
  101083. return;
  101084. }
  101085. this._captureAnimationsTime = value;
  101086. if (value) {
  101087. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101088. _this._animationsTime.endMonitoring();
  101089. });
  101090. }
  101091. else {
  101092. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101093. this._onAfterAnimationsObserver = null;
  101094. }
  101095. },
  101096. enumerable: true,
  101097. configurable: true
  101098. });
  101099. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101100. /**
  101101. * Gets the perf counter used for frame time capture
  101102. */
  101103. get: function () {
  101104. return this._frameTime;
  101105. },
  101106. enumerable: true,
  101107. configurable: true
  101108. });
  101109. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101110. /**
  101111. * Gets the frame time capture status
  101112. */
  101113. get: function () {
  101114. return this._captureFrameTime;
  101115. },
  101116. /**
  101117. * Enable or disable the frame time capture
  101118. */
  101119. set: function (value) {
  101120. this._captureFrameTime = value;
  101121. },
  101122. enumerable: true,
  101123. configurable: true
  101124. });
  101125. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101126. /**
  101127. * Gets the perf counter used for inter-frames time capture
  101128. */
  101129. get: function () {
  101130. return this._interFrameTime;
  101131. },
  101132. enumerable: true,
  101133. configurable: true
  101134. });
  101135. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101136. /**
  101137. * Gets the inter-frames time capture status
  101138. */
  101139. get: function () {
  101140. return this._captureInterFrameTime;
  101141. },
  101142. /**
  101143. * Enable or disable the inter-frames time capture
  101144. */
  101145. set: function (value) {
  101146. this._captureInterFrameTime = value;
  101147. },
  101148. enumerable: true,
  101149. configurable: true
  101150. });
  101151. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101152. /**
  101153. * Gets the perf counter used for render time capture
  101154. */
  101155. get: function () {
  101156. return this._renderTime;
  101157. },
  101158. enumerable: true,
  101159. configurable: true
  101160. });
  101161. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101162. /**
  101163. * Gets the render time capture status
  101164. */
  101165. get: function () {
  101166. return this._captureRenderTime;
  101167. },
  101168. /**
  101169. * Enable or disable the render time capture
  101170. */
  101171. set: function (value) {
  101172. var _this = this;
  101173. if (value === this._captureRenderTime) {
  101174. return;
  101175. }
  101176. this._captureRenderTime = value;
  101177. if (value) {
  101178. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101179. _this._renderTime.beginMonitoring();
  101180. BABYLON.Tools.StartPerformanceCounter("Main render");
  101181. });
  101182. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101183. _this._renderTime.endMonitoring(false);
  101184. BABYLON.Tools.EndPerformanceCounter("Main render");
  101185. });
  101186. }
  101187. else {
  101188. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101189. this._onBeforeDrawPhaseObserver = null;
  101190. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101191. this._onAfterDrawPhaseObserver = null;
  101192. }
  101193. },
  101194. enumerable: true,
  101195. configurable: true
  101196. });
  101197. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101198. /**
  101199. * Gets the perf counter used for camera render time capture
  101200. */
  101201. get: function () {
  101202. return this._cameraRenderTime;
  101203. },
  101204. enumerable: true,
  101205. configurable: true
  101206. });
  101207. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101208. /**
  101209. * Gets the camera render time capture status
  101210. */
  101211. get: function () {
  101212. return this._captureCameraRenderTime;
  101213. },
  101214. /**
  101215. * Enable or disable the camera render time capture
  101216. */
  101217. set: function (value) {
  101218. var _this = this;
  101219. if (value === this._captureCameraRenderTime) {
  101220. return;
  101221. }
  101222. this._captureCameraRenderTime = value;
  101223. if (value) {
  101224. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101225. _this._cameraRenderTime.beginMonitoring();
  101226. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101227. });
  101228. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101229. _this._cameraRenderTime.endMonitoring(false);
  101230. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101231. });
  101232. }
  101233. else {
  101234. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101235. this._onBeforeCameraRenderObserver = null;
  101236. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101237. this._onAfterCameraRenderObserver = null;
  101238. }
  101239. },
  101240. enumerable: true,
  101241. configurable: true
  101242. });
  101243. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101244. /**
  101245. * Gets the perf counter used for draw calls
  101246. */
  101247. get: function () {
  101248. return this.scene.getEngine()._drawCalls;
  101249. },
  101250. enumerable: true,
  101251. configurable: true
  101252. });
  101253. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101254. /**
  101255. * Gets the perf counter used for texture collisions
  101256. */
  101257. get: function () {
  101258. return this.scene.getEngine()._textureCollisions;
  101259. },
  101260. enumerable: true,
  101261. configurable: true
  101262. });
  101263. SceneInstrumentation.prototype.dispose = function () {
  101264. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101265. this._onAfterRenderObserver = null;
  101266. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101267. this._onBeforeActiveMeshesEvaluationObserver = null;
  101268. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101269. this._onAfterActiveMeshesEvaluationObserver = null;
  101270. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101271. this._onBeforeRenderTargetsRenderObserver = null;
  101272. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101273. this._onAfterRenderTargetsRenderObserver = null;
  101274. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101275. this._onBeforeAnimationsObserver = null;
  101276. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101277. this._onBeforeParticlesRenderingObserver = null;
  101278. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101279. this._onAfterParticlesRenderingObserver = null;
  101280. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101281. this._onBeforeSpritesRenderingObserver = null;
  101282. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101283. this._onAfterSpritesRenderingObserver = null;
  101284. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101285. this._onBeforeDrawPhaseObserver = null;
  101286. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101287. this._onAfterDrawPhaseObserver = null;
  101288. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101289. this._onBeforePhysicsObserver = null;
  101290. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101291. this._onAfterPhysicsObserver = null;
  101292. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101293. this._onAfterAnimationsObserver = null;
  101294. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101295. this._onBeforeCameraRenderObserver = null;
  101296. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101297. this._onAfterCameraRenderObserver = null;
  101298. this.scene = null;
  101299. };
  101300. return SceneInstrumentation;
  101301. }());
  101302. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101303. })(BABYLON || (BABYLON = {}));
  101304. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101305. var BABYLON;
  101306. (function (BABYLON) {
  101307. /**
  101308. * @hidden
  101309. **/
  101310. var _TimeToken = /** @class */ (function () {
  101311. function _TimeToken() {
  101312. this._timeElapsedQueryEnded = false;
  101313. }
  101314. return _TimeToken;
  101315. }());
  101316. BABYLON._TimeToken = _TimeToken;
  101317. })(BABYLON || (BABYLON = {}));
  101318. //# sourceMappingURL=babylon.timeToken.js.map
  101319. var BABYLON;
  101320. (function (BABYLON) {
  101321. /**
  101322. * Background material defines definition.
  101323. * @hidden Mainly internal Use
  101324. */
  101325. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101326. __extends(BackgroundMaterialDefines, _super);
  101327. /**
  101328. * Constructor of the defines.
  101329. */
  101330. function BackgroundMaterialDefines() {
  101331. var _this = _super.call(this) || this;
  101332. /**
  101333. * True if the diffuse texture is in use.
  101334. */
  101335. _this.DIFFUSE = false;
  101336. /**
  101337. * The direct UV channel to use.
  101338. */
  101339. _this.DIFFUSEDIRECTUV = 0;
  101340. /**
  101341. * True if the diffuse texture is in gamma space.
  101342. */
  101343. _this.GAMMADIFFUSE = false;
  101344. /**
  101345. * True if the diffuse texture has opacity in the alpha channel.
  101346. */
  101347. _this.DIFFUSEHASALPHA = false;
  101348. /**
  101349. * True if you want the material to fade to transparent at grazing angle.
  101350. */
  101351. _this.OPACITYFRESNEL = false;
  101352. /**
  101353. * True if an extra blur needs to be added in the reflection.
  101354. */
  101355. _this.REFLECTIONBLUR = false;
  101356. /**
  101357. * True if you want the material to fade to reflection at grazing angle.
  101358. */
  101359. _this.REFLECTIONFRESNEL = false;
  101360. /**
  101361. * True if you want the material to falloff as far as you move away from the scene center.
  101362. */
  101363. _this.REFLECTIONFALLOFF = false;
  101364. /**
  101365. * False if the current Webgl implementation does not support the texture lod extension.
  101366. */
  101367. _this.TEXTURELODSUPPORT = false;
  101368. /**
  101369. * True to ensure the data are premultiplied.
  101370. */
  101371. _this.PREMULTIPLYALPHA = false;
  101372. /**
  101373. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101374. */
  101375. _this.USERGBCOLOR = false;
  101376. /**
  101377. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101378. * stays aligned with the desired configuration.
  101379. */
  101380. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101381. /**
  101382. * True to add noise in order to reduce the banding effect.
  101383. */
  101384. _this.NOISE = false;
  101385. /**
  101386. * is the reflection texture in BGR color scheme?
  101387. * Mainly used to solve a bug in ios10 video tag
  101388. */
  101389. _this.REFLECTIONBGR = false;
  101390. _this.IMAGEPROCESSING = false;
  101391. _this.VIGNETTE = false;
  101392. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101393. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101394. _this.TONEMAPPING = false;
  101395. _this.CONTRAST = false;
  101396. _this.COLORCURVES = false;
  101397. _this.COLORGRADING = false;
  101398. _this.COLORGRADING3D = false;
  101399. _this.SAMPLER3DGREENDEPTH = false;
  101400. _this.SAMPLER3DBGRMAP = false;
  101401. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101402. _this.EXPOSURE = false;
  101403. // Reflection.
  101404. _this.REFLECTION = false;
  101405. _this.REFLECTIONMAP_3D = false;
  101406. _this.REFLECTIONMAP_SPHERICAL = false;
  101407. _this.REFLECTIONMAP_PLANAR = false;
  101408. _this.REFLECTIONMAP_CUBIC = false;
  101409. _this.REFLECTIONMAP_PROJECTION = false;
  101410. _this.REFLECTIONMAP_SKYBOX = false;
  101411. _this.REFLECTIONMAP_EXPLICIT = false;
  101412. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101413. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101414. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101415. _this.INVERTCUBICMAP = false;
  101416. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101417. _this.LODINREFLECTIONALPHA = false;
  101418. _this.GAMMAREFLECTION = false;
  101419. _this.RGBDREFLECTION = false;
  101420. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101421. // Default BJS.
  101422. _this.MAINUV1 = false;
  101423. _this.MAINUV2 = false;
  101424. _this.UV1 = false;
  101425. _this.UV2 = false;
  101426. _this.CLIPPLANE = false;
  101427. _this.POINTSIZE = false;
  101428. _this.FOG = false;
  101429. _this.NORMAL = false;
  101430. _this.NUM_BONE_INFLUENCERS = 0;
  101431. _this.BonesPerMesh = 0;
  101432. _this.INSTANCES = false;
  101433. _this.SHADOWFLOAT = false;
  101434. _this.rebuild();
  101435. return _this;
  101436. }
  101437. return BackgroundMaterialDefines;
  101438. }(BABYLON.MaterialDefines));
  101439. /**
  101440. * Background material used to create an efficient environement around your scene.
  101441. */
  101442. var BackgroundMaterial = /** @class */ (function (_super) {
  101443. __extends(BackgroundMaterial, _super);
  101444. /**
  101445. * Instantiates a Background Material in the given scene
  101446. * @param name The friendly name of the material
  101447. * @param scene The scene to add the material to
  101448. */
  101449. function BackgroundMaterial(name, scene) {
  101450. var _this = _super.call(this, name, scene) || this;
  101451. /**
  101452. * Key light Color (multiply against the environement texture)
  101453. */
  101454. _this.primaryColor = BABYLON.Color3.White();
  101455. _this._primaryColorShadowLevel = 0;
  101456. _this._primaryColorHighlightLevel = 0;
  101457. /**
  101458. * Reflection Texture used in the material.
  101459. * Should be author in a specific way for the best result (refer to the documentation).
  101460. */
  101461. _this.reflectionTexture = null;
  101462. /**
  101463. * Reflection Texture level of blur.
  101464. *
  101465. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101466. * texture twice.
  101467. */
  101468. _this.reflectionBlur = 0;
  101469. /**
  101470. * Diffuse Texture used in the material.
  101471. * Should be author in a specific way for the best result (refer to the documentation).
  101472. */
  101473. _this.diffuseTexture = null;
  101474. _this._shadowLights = null;
  101475. /**
  101476. * Specify the list of lights casting shadow on the material.
  101477. * All scene shadow lights will be included if null.
  101478. */
  101479. _this.shadowLights = null;
  101480. /**
  101481. * Helps adjusting the shadow to a softer level if required.
  101482. * 0 means black shadows and 1 means no shadows.
  101483. */
  101484. _this.shadowLevel = 0;
  101485. /**
  101486. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101487. * It is usually zero but might be interesting to modify according to your setup.
  101488. */
  101489. _this.sceneCenter = BABYLON.Vector3.Zero();
  101490. /**
  101491. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101492. * This helps ensuring a nice transition when the camera goes under the ground.
  101493. */
  101494. _this.opacityFresnel = true;
  101495. /**
  101496. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101497. * This helps adding a mirror texture on the ground.
  101498. */
  101499. _this.reflectionFresnel = false;
  101500. /**
  101501. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101502. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101503. */
  101504. _this.reflectionFalloffDistance = 0.0;
  101505. /**
  101506. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101507. */
  101508. _this.reflectionAmount = 1.0;
  101509. /**
  101510. * This specifies the weight of the reflection at grazing angle.
  101511. */
  101512. _this.reflectionReflectance0 = 0.05;
  101513. /**
  101514. * This specifies the weight of the reflection at a perpendicular point of view.
  101515. */
  101516. _this.reflectionReflectance90 = 0.5;
  101517. /**
  101518. * Helps to directly use the maps channels instead of their level.
  101519. */
  101520. _this.useRGBColor = true;
  101521. /**
  101522. * This helps reducing the banding effect that could occur on the background.
  101523. */
  101524. _this.enableNoise = false;
  101525. _this._fovMultiplier = 1.0;
  101526. /**
  101527. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101528. */
  101529. _this.useEquirectangularFOV = false;
  101530. _this._maxSimultaneousLights = 4;
  101531. /**
  101532. * Number of Simultaneous lights allowed on the material.
  101533. */
  101534. _this.maxSimultaneousLights = 4;
  101535. /**
  101536. * Keep track of the image processing observer to allow dispose and replace.
  101537. */
  101538. _this._imageProcessingObserver = null;
  101539. /**
  101540. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101541. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101542. */
  101543. _this.switchToBGR = false;
  101544. // Temp values kept as cache in the material.
  101545. _this._renderTargets = new BABYLON.SmartArray(16);
  101546. _this._reflectionControls = BABYLON.Vector4.Zero();
  101547. _this._white = BABYLON.Color3.White();
  101548. _this._primaryShadowColor = BABYLON.Color3.Black();
  101549. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101550. // Setup the default processing configuration to the scene.
  101551. _this._attachImageProcessingConfiguration(null);
  101552. _this.getRenderTargetTextures = function () {
  101553. _this._renderTargets.reset();
  101554. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101555. _this._renderTargets.push(_this._diffuseTexture);
  101556. }
  101557. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101558. _this._renderTargets.push(_this._reflectionTexture);
  101559. }
  101560. return _this._renderTargets;
  101561. };
  101562. return _this;
  101563. }
  101564. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101565. /**
  101566. * Experimental Internal Use Only.
  101567. *
  101568. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101569. * This acts as a helper to set the primary color to a more "human friendly" value.
  101570. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101571. * output color as close as possible from the chosen value.
  101572. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101573. * part of lighting setup.)
  101574. */
  101575. get: function () {
  101576. return this.__perceptualColor;
  101577. },
  101578. set: function (value) {
  101579. this.__perceptualColor = value;
  101580. this._computePrimaryColorFromPerceptualColor();
  101581. this._markAllSubMeshesAsLightsDirty();
  101582. },
  101583. enumerable: true,
  101584. configurable: true
  101585. });
  101586. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101587. /**
  101588. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101589. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101590. */
  101591. get: function () {
  101592. return this._primaryColorShadowLevel;
  101593. },
  101594. set: function (value) {
  101595. this._primaryColorShadowLevel = value;
  101596. this._computePrimaryColors();
  101597. this._markAllSubMeshesAsLightsDirty();
  101598. },
  101599. enumerable: true,
  101600. configurable: true
  101601. });
  101602. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101603. /**
  101604. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101605. * The primary color is used at the level chosen to define what the white area would look.
  101606. */
  101607. get: function () {
  101608. return this._primaryColorHighlightLevel;
  101609. },
  101610. set: function (value) {
  101611. this._primaryColorHighlightLevel = value;
  101612. this._computePrimaryColors();
  101613. this._markAllSubMeshesAsLightsDirty();
  101614. },
  101615. enumerable: true,
  101616. configurable: true
  101617. });
  101618. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101619. /**
  101620. * Sets the reflection reflectance fresnel values according to the default standard
  101621. * empirically know to work well :-)
  101622. */
  101623. set: function (value) {
  101624. var reflectionWeight = value;
  101625. if (reflectionWeight < 0.5) {
  101626. reflectionWeight = reflectionWeight * 2.0;
  101627. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101628. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101629. }
  101630. else {
  101631. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101632. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101633. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101634. }
  101635. },
  101636. enumerable: true,
  101637. configurable: true
  101638. });
  101639. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101640. /**
  101641. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101642. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101643. * Recommended to be keep at 1.0 except for special cases.
  101644. */
  101645. get: function () {
  101646. return this._fovMultiplier;
  101647. },
  101648. set: function (value) {
  101649. if (isNaN(value)) {
  101650. value = 1.0;
  101651. }
  101652. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101653. },
  101654. enumerable: true,
  101655. configurable: true
  101656. });
  101657. /**
  101658. * Attaches a new image processing configuration to the PBR Material.
  101659. * @param configuration (if null the scene configuration will be use)
  101660. */
  101661. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101662. var _this = this;
  101663. if (configuration === this._imageProcessingConfiguration) {
  101664. return;
  101665. }
  101666. // Detaches observer.
  101667. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101668. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101669. }
  101670. // Pick the scene configuration if needed.
  101671. if (!configuration) {
  101672. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101673. }
  101674. else {
  101675. this._imageProcessingConfiguration = configuration;
  101676. }
  101677. // Attaches observer.
  101678. if (this._imageProcessingConfiguration) {
  101679. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101680. _this._computePrimaryColorFromPerceptualColor();
  101681. _this._markAllSubMeshesAsImageProcessingDirty();
  101682. });
  101683. }
  101684. };
  101685. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101686. /**
  101687. * Gets the image processing configuration used either in this material.
  101688. */
  101689. get: function () {
  101690. return this._imageProcessingConfiguration;
  101691. },
  101692. /**
  101693. * Sets the Default image processing configuration used either in the this material.
  101694. *
  101695. * If sets to null, the scene one is in use.
  101696. */
  101697. set: function (value) {
  101698. this._attachImageProcessingConfiguration(value);
  101699. // Ensure the effect will be rebuilt.
  101700. this._markAllSubMeshesAsTexturesDirty();
  101701. },
  101702. enumerable: true,
  101703. configurable: true
  101704. });
  101705. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101706. /**
  101707. * Gets wether the color curves effect is enabled.
  101708. */
  101709. get: function () {
  101710. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101711. },
  101712. /**
  101713. * Sets wether the color curves effect is enabled.
  101714. */
  101715. set: function (value) {
  101716. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101717. },
  101718. enumerable: true,
  101719. configurable: true
  101720. });
  101721. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101722. /**
  101723. * Gets wether the color grading effect is enabled.
  101724. */
  101725. get: function () {
  101726. return this.imageProcessingConfiguration.colorGradingEnabled;
  101727. },
  101728. /**
  101729. * Gets wether the color grading effect is enabled.
  101730. */
  101731. set: function (value) {
  101732. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101733. },
  101734. enumerable: true,
  101735. configurable: true
  101736. });
  101737. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101738. /**
  101739. * Gets wether tonemapping is enabled or not.
  101740. */
  101741. get: function () {
  101742. return this._imageProcessingConfiguration.toneMappingEnabled;
  101743. },
  101744. /**
  101745. * Sets wether tonemapping is enabled or not
  101746. */
  101747. set: function (value) {
  101748. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101749. },
  101750. enumerable: true,
  101751. configurable: true
  101752. });
  101753. ;
  101754. ;
  101755. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101756. /**
  101757. * The camera exposure used on this material.
  101758. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101759. * This corresponds to a photographic exposure.
  101760. */
  101761. get: function () {
  101762. return this._imageProcessingConfiguration.exposure;
  101763. },
  101764. /**
  101765. * The camera exposure used on this material.
  101766. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101767. * This corresponds to a photographic exposure.
  101768. */
  101769. set: function (value) {
  101770. this._imageProcessingConfiguration.exposure = value;
  101771. },
  101772. enumerable: true,
  101773. configurable: true
  101774. });
  101775. ;
  101776. ;
  101777. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101778. /**
  101779. * Gets The camera contrast used on this material.
  101780. */
  101781. get: function () {
  101782. return this._imageProcessingConfiguration.contrast;
  101783. },
  101784. /**
  101785. * Sets The camera contrast used on this material.
  101786. */
  101787. set: function (value) {
  101788. this._imageProcessingConfiguration.contrast = value;
  101789. },
  101790. enumerable: true,
  101791. configurable: true
  101792. });
  101793. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101794. /**
  101795. * Gets the Color Grading 2D Lookup Texture.
  101796. */
  101797. get: function () {
  101798. return this._imageProcessingConfiguration.colorGradingTexture;
  101799. },
  101800. /**
  101801. * Sets the Color Grading 2D Lookup Texture.
  101802. */
  101803. set: function (value) {
  101804. this.imageProcessingConfiguration.colorGradingTexture = value;
  101805. },
  101806. enumerable: true,
  101807. configurable: true
  101808. });
  101809. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101810. /**
  101811. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101812. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101813. * 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;
  101814. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101815. */
  101816. get: function () {
  101817. return this.imageProcessingConfiguration.colorCurves;
  101818. },
  101819. /**
  101820. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101821. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101822. * 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;
  101823. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101824. */
  101825. set: function (value) {
  101826. this.imageProcessingConfiguration.colorCurves = value;
  101827. },
  101828. enumerable: true,
  101829. configurable: true
  101830. });
  101831. /**
  101832. * The entire material has been created in order to prevent overdraw.
  101833. * @returns false
  101834. */
  101835. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101836. return true;
  101837. };
  101838. /**
  101839. * The entire material has been created in order to prevent overdraw.
  101840. * @returns true if blending is enable
  101841. */
  101842. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101843. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101844. };
  101845. /**
  101846. * Checks wether the material is ready to be rendered for a given mesh.
  101847. * @param mesh The mesh to render
  101848. * @param subMesh The submesh to check against
  101849. * @param useInstances Specify wether or not the material is used with instances
  101850. * @returns true if all the dependencies are ready (Textures, Effects...)
  101851. */
  101852. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101853. var _this = this;
  101854. if (useInstances === void 0) { useInstances = false; }
  101855. if (subMesh.effect && this.isFrozen) {
  101856. if (this._wasPreviouslyReady) {
  101857. return true;
  101858. }
  101859. }
  101860. if (!subMesh._materialDefines) {
  101861. subMesh._materialDefines = new BackgroundMaterialDefines();
  101862. }
  101863. var scene = this.getScene();
  101864. var defines = subMesh._materialDefines;
  101865. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101866. if (defines._renderId === scene.getRenderId()) {
  101867. return true;
  101868. }
  101869. }
  101870. var engine = scene.getEngine();
  101871. // Lights
  101872. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101873. defines._needNormals = true;
  101874. // Textures
  101875. if (defines._areTexturesDirty) {
  101876. defines._needUVs = false;
  101877. if (scene.texturesEnabled) {
  101878. if (scene.getEngine().getCaps().textureLOD) {
  101879. defines.TEXTURELODSUPPORT = true;
  101880. }
  101881. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101882. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101883. return false;
  101884. }
  101885. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101886. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101887. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101888. defines.OPACITYFRESNEL = this._opacityFresnel;
  101889. }
  101890. else {
  101891. defines.DIFFUSE = false;
  101892. defines.DIFFUSEHASALPHA = false;
  101893. defines.GAMMADIFFUSE = false;
  101894. defines.OPACITYFRESNEL = false;
  101895. }
  101896. var reflectionTexture = this._reflectionTexture;
  101897. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101898. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101899. return false;
  101900. }
  101901. defines.REFLECTION = true;
  101902. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101903. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101904. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101905. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101906. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101907. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101908. defines.REFLECTIONBGR = this.switchToBGR;
  101909. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101910. defines.INVERTCUBICMAP = true;
  101911. }
  101912. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101913. switch (reflectionTexture.coordinatesMode) {
  101914. case BABYLON.Texture.EXPLICIT_MODE:
  101915. defines.REFLECTIONMAP_EXPLICIT = true;
  101916. break;
  101917. case BABYLON.Texture.PLANAR_MODE:
  101918. defines.REFLECTIONMAP_PLANAR = true;
  101919. break;
  101920. case BABYLON.Texture.PROJECTION_MODE:
  101921. defines.REFLECTIONMAP_PROJECTION = true;
  101922. break;
  101923. case BABYLON.Texture.SKYBOX_MODE:
  101924. defines.REFLECTIONMAP_SKYBOX = true;
  101925. break;
  101926. case BABYLON.Texture.SPHERICAL_MODE:
  101927. defines.REFLECTIONMAP_SPHERICAL = true;
  101928. break;
  101929. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101930. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101931. break;
  101932. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101933. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  101934. break;
  101935. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101936. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101937. break;
  101938. case BABYLON.Texture.CUBIC_MODE:
  101939. case BABYLON.Texture.INVCUBIC_MODE:
  101940. default:
  101941. defines.REFLECTIONMAP_CUBIC = true;
  101942. break;
  101943. }
  101944. if (this.reflectionFresnel) {
  101945. defines.REFLECTIONFRESNEL = true;
  101946. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  101947. this._reflectionControls.x = this.reflectionAmount;
  101948. this._reflectionControls.y = this.reflectionReflectance0;
  101949. this._reflectionControls.z = this.reflectionReflectance90;
  101950. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  101951. }
  101952. else {
  101953. defines.REFLECTIONFRESNEL = false;
  101954. defines.REFLECTIONFALLOFF = false;
  101955. }
  101956. }
  101957. else {
  101958. defines.REFLECTION = false;
  101959. defines.REFLECTIONFRESNEL = false;
  101960. defines.REFLECTIONFALLOFF = false;
  101961. defines.REFLECTIONBLUR = false;
  101962. defines.REFLECTIONMAP_3D = false;
  101963. defines.REFLECTIONMAP_SPHERICAL = false;
  101964. defines.REFLECTIONMAP_PLANAR = false;
  101965. defines.REFLECTIONMAP_CUBIC = false;
  101966. defines.REFLECTIONMAP_PROJECTION = false;
  101967. defines.REFLECTIONMAP_SKYBOX = false;
  101968. defines.REFLECTIONMAP_EXPLICIT = false;
  101969. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101970. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101971. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101972. defines.INVERTCUBICMAP = false;
  101973. defines.REFLECTIONMAP_OPPOSITEZ = false;
  101974. defines.LODINREFLECTIONALPHA = false;
  101975. defines.GAMMAREFLECTION = false;
  101976. defines.RGBDREFLECTION = false;
  101977. }
  101978. }
  101979. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  101980. defines.USERGBCOLOR = this._useRGBColor;
  101981. defines.NOISE = this._enableNoise;
  101982. }
  101983. if (defines._areLightsDirty) {
  101984. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  101985. }
  101986. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  101987. if (!this._imageProcessingConfiguration.isReady()) {
  101988. return false;
  101989. }
  101990. this._imageProcessingConfiguration.prepareDefines(defines);
  101991. }
  101992. // Misc.
  101993. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  101994. // Values that need to be evaluated on every frame
  101995. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  101996. // Attribs
  101997. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  101998. if (mesh) {
  101999. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102000. mesh.createNormals(true);
  102001. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102002. }
  102003. }
  102004. }
  102005. // Get correct effect
  102006. if (defines.isDirty) {
  102007. defines.markAsProcessed();
  102008. scene.resetCachedMaterial();
  102009. // Fallbacks
  102010. var fallbacks = new BABYLON.EffectFallbacks();
  102011. if (defines.FOG) {
  102012. fallbacks.addFallback(0, "FOG");
  102013. }
  102014. if (defines.POINTSIZE) {
  102015. fallbacks.addFallback(1, "POINTSIZE");
  102016. }
  102017. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102018. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102019. fallbacks.addCPUSkinningFallback(0, mesh);
  102020. }
  102021. //Attributes
  102022. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102023. if (defines.NORMAL) {
  102024. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102025. }
  102026. if (defines.UV1) {
  102027. attribs.push(BABYLON.VertexBuffer.UVKind);
  102028. }
  102029. if (defines.UV2) {
  102030. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102031. }
  102032. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102033. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102034. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102035. "vFogInfos", "vFogColor", "pointSize",
  102036. "vClipPlane", "mBones",
  102037. "vPrimaryColor", "vPrimaryColorShadow",
  102038. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102039. "shadowLevel", "alpha",
  102040. "vBackgroundCenter", "vReflectionControl",
  102041. "vDiffuseInfos", "diffuseMatrix",
  102042. ];
  102043. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102044. var uniformBuffers = ["Material", "Scene"];
  102045. if (BABYLON.ImageProcessingConfiguration) {
  102046. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102047. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102048. }
  102049. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102050. uniformsNames: uniforms,
  102051. uniformBuffersNames: uniformBuffers,
  102052. samplers: samplers,
  102053. defines: defines,
  102054. maxSimultaneousLights: this._maxSimultaneousLights
  102055. });
  102056. var onCompiled = function (effect) {
  102057. if (_this.onCompiled) {
  102058. _this.onCompiled(effect);
  102059. }
  102060. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102061. };
  102062. var join = defines.toString();
  102063. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102064. attributes: attribs,
  102065. uniformsNames: uniforms,
  102066. uniformBuffersNames: uniformBuffers,
  102067. samplers: samplers,
  102068. defines: join,
  102069. fallbacks: fallbacks,
  102070. onCompiled: onCompiled,
  102071. onError: this.onError,
  102072. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102073. }, engine), defines);
  102074. this.buildUniformLayout();
  102075. }
  102076. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102077. return false;
  102078. }
  102079. defines._renderId = scene.getRenderId();
  102080. this._wasPreviouslyReady = true;
  102081. return true;
  102082. };
  102083. /**
  102084. * Compute the primary color according to the chosen perceptual color.
  102085. */
  102086. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102087. if (!this.__perceptualColor) {
  102088. return;
  102089. }
  102090. this._primaryColor.copyFrom(this.__perceptualColor);
  102091. // Revert gamma space.
  102092. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102093. // Revert image processing configuration.
  102094. if (this._imageProcessingConfiguration) {
  102095. // Revert Exposure.
  102096. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102097. }
  102098. this._computePrimaryColors();
  102099. };
  102100. /**
  102101. * Compute the highlights and shadow colors according to their chosen levels.
  102102. */
  102103. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102104. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102105. return;
  102106. }
  102107. // Find the highlight color based on the configuration.
  102108. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102109. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102110. // Find the shadow color based on the configuration.
  102111. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102112. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102113. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102114. };
  102115. /**
  102116. * Build the uniform buffer used in the material.
  102117. */
  102118. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102119. // Order is important !
  102120. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102121. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102122. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102123. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102124. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102125. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102126. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102127. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102128. this._uniformBuffer.addUniform("pointSize", 1);
  102129. this._uniformBuffer.addUniform("shadowLevel", 1);
  102130. this._uniformBuffer.addUniform("alpha", 1);
  102131. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102132. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102133. this._uniformBuffer.create();
  102134. };
  102135. /**
  102136. * Unbind the material.
  102137. */
  102138. BackgroundMaterial.prototype.unbind = function () {
  102139. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102140. this._uniformBuffer.setTexture("diffuseSampler", null);
  102141. }
  102142. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102143. this._uniformBuffer.setTexture("reflectionSampler", null);
  102144. }
  102145. _super.prototype.unbind.call(this);
  102146. };
  102147. /**
  102148. * Bind only the world matrix to the material.
  102149. * @param world The world matrix to bind.
  102150. */
  102151. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102152. this._activeEffect.setMatrix("world", world);
  102153. };
  102154. /**
  102155. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102156. * @param world The world matrix to bind.
  102157. * @param subMesh The submesh to bind for.
  102158. */
  102159. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102160. var scene = this.getScene();
  102161. var defines = subMesh._materialDefines;
  102162. if (!defines) {
  102163. return;
  102164. }
  102165. var effect = subMesh.effect;
  102166. if (!effect) {
  102167. return;
  102168. }
  102169. this._activeEffect = effect;
  102170. // Matrices
  102171. this.bindOnlyWorldMatrix(world);
  102172. // Bones
  102173. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102174. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102175. if (mustRebind) {
  102176. this._uniformBuffer.bindToEffect(effect, "Material");
  102177. this.bindViewProjection(effect);
  102178. var reflectionTexture = this._reflectionTexture;
  102179. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102180. // Texture uniforms
  102181. if (scene.texturesEnabled) {
  102182. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102183. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102184. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102185. }
  102186. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102187. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102188. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102189. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102190. }
  102191. }
  102192. if (this.shadowLevel > 0) {
  102193. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102194. }
  102195. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102196. // Point size
  102197. if (this.pointsCloud) {
  102198. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102199. }
  102200. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102201. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102202. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102203. }
  102204. else {
  102205. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102206. }
  102207. }
  102208. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102209. // Textures
  102210. if (scene.texturesEnabled) {
  102211. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102212. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102213. }
  102214. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102215. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102216. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102217. }
  102218. else if (!defines.REFLECTIONBLUR) {
  102219. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102220. }
  102221. else {
  102222. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102223. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102224. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102225. }
  102226. if (defines.REFLECTIONFRESNEL) {
  102227. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102228. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102229. }
  102230. }
  102231. }
  102232. // Clip plane
  102233. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102234. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102235. }
  102236. if (mustRebind || !this.isFrozen) {
  102237. if (scene.lightsEnabled) {
  102238. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102239. }
  102240. // View
  102241. this.bindView(effect);
  102242. // Fog
  102243. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102244. // image processing
  102245. if (this._imageProcessingConfiguration) {
  102246. this._imageProcessingConfiguration.bind(this._activeEffect);
  102247. }
  102248. }
  102249. this._uniformBuffer.update();
  102250. this._afterBind(mesh, this._activeEffect);
  102251. };
  102252. /**
  102253. * Dispose the material.
  102254. * @param forceDisposeEffect Force disposal of the associated effect.
  102255. * @param forceDisposeTextures Force disposal of the associated textures.
  102256. */
  102257. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102258. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102259. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102260. if (forceDisposeTextures) {
  102261. if (this.diffuseTexture) {
  102262. this.diffuseTexture.dispose();
  102263. }
  102264. if (this.reflectionTexture) {
  102265. this.reflectionTexture.dispose();
  102266. }
  102267. }
  102268. this._renderTargets.dispose();
  102269. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102270. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102271. }
  102272. _super.prototype.dispose.call(this, forceDisposeEffect);
  102273. };
  102274. /**
  102275. * Clones the material.
  102276. * @param name The cloned name.
  102277. * @returns The cloned material.
  102278. */
  102279. BackgroundMaterial.prototype.clone = function (name) {
  102280. var _this = this;
  102281. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102282. };
  102283. /**
  102284. * Serializes the current material to its JSON representation.
  102285. * @returns The JSON representation.
  102286. */
  102287. BackgroundMaterial.prototype.serialize = function () {
  102288. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102289. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102290. return serializationObject;
  102291. };
  102292. /**
  102293. * Gets the class name of the material
  102294. * @returns "BackgroundMaterial"
  102295. */
  102296. BackgroundMaterial.prototype.getClassName = function () {
  102297. return "BackgroundMaterial";
  102298. };
  102299. /**
  102300. * Parse a JSON input to create back a background material.
  102301. * @param source The JSON data to parse
  102302. * @param scene The scene to create the parsed material in
  102303. * @param rootUrl The root url of the assets the material depends upon
  102304. * @returns the instantiated BackgroundMaterial.
  102305. */
  102306. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102307. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102308. };
  102309. /**
  102310. * Standard reflectance value at parallel view angle.
  102311. */
  102312. BackgroundMaterial.StandardReflectance0 = 0.05;
  102313. /**
  102314. * Standard reflectance value at grazing angle.
  102315. */
  102316. BackgroundMaterial.StandardReflectance90 = 0.5;
  102317. __decorate([
  102318. BABYLON.serializeAsColor3()
  102319. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102320. __decorate([
  102321. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102322. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102323. __decorate([
  102324. BABYLON.serializeAsColor3()
  102325. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102326. __decorate([
  102327. BABYLON.serialize()
  102328. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102329. __decorate([
  102330. BABYLON.serialize()
  102331. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102332. __decorate([
  102333. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102334. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102335. __decorate([
  102336. BABYLON.serializeAsTexture()
  102337. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102338. __decorate([
  102339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102340. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102341. __decorate([
  102342. BABYLON.serialize()
  102343. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102344. __decorate([
  102345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102346. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102347. __decorate([
  102348. BABYLON.serializeAsTexture()
  102349. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102350. __decorate([
  102351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102352. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102353. __decorate([
  102354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102355. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102356. __decorate([
  102357. BABYLON.serialize()
  102358. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102359. __decorate([
  102360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102361. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102362. __decorate([
  102363. BABYLON.serializeAsVector3()
  102364. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102365. __decorate([
  102366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102367. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102368. __decorate([
  102369. BABYLON.serialize()
  102370. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102371. __decorate([
  102372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102373. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102374. __decorate([
  102375. BABYLON.serialize()
  102376. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102377. __decorate([
  102378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102379. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102380. __decorate([
  102381. BABYLON.serialize()
  102382. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102383. __decorate([
  102384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102385. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102386. __decorate([
  102387. BABYLON.serialize()
  102388. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102389. __decorate([
  102390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102391. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102392. __decorate([
  102393. BABYLON.serialize()
  102394. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102395. __decorate([
  102396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102397. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102398. __decorate([
  102399. BABYLON.serialize()
  102400. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102401. __decorate([
  102402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102403. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102404. __decorate([
  102405. BABYLON.serialize()
  102406. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102407. __decorate([
  102408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102409. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102410. __decorate([
  102411. BABYLON.serialize()
  102412. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102413. __decorate([
  102414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102415. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102416. __decorate([
  102417. BABYLON.serialize()
  102418. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102419. __decorate([
  102420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102421. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102422. __decorate([
  102423. BABYLON.serializeAsImageProcessingConfiguration()
  102424. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102425. return BackgroundMaterial;
  102426. }(BABYLON.PushMaterial));
  102427. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102428. })(BABYLON || (BABYLON = {}));
  102429. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102430. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102431. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102432. s = arguments[i];
  102433. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102434. t[p] = s[p];
  102435. }
  102436. return t;
  102437. };
  102438. var BABYLON;
  102439. (function (BABYLON) {
  102440. /**
  102441. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102442. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102443. * It also helps with the default setup of your imageProcessing configuration.
  102444. */
  102445. var EnvironmentHelper = /** @class */ (function () {
  102446. /**
  102447. * constructor
  102448. * @param options
  102449. * @param scene The scene to add the material to
  102450. */
  102451. function EnvironmentHelper(options, scene) {
  102452. var _this = this;
  102453. this._errorHandler = function (message, exception) {
  102454. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102455. };
  102456. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102457. this._scene = scene;
  102458. this.onErrorObservable = new BABYLON.Observable();
  102459. this._setupBackground();
  102460. this._setupImageProcessing();
  102461. }
  102462. /**
  102463. * Creates the default options for the helper.
  102464. */
  102465. EnvironmentHelper._getDefaultOptions = function () {
  102466. return {
  102467. createGround: true,
  102468. groundSize: 15,
  102469. groundTexture: this._groundTextureCDNUrl,
  102470. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102471. groundOpacity: 0.9,
  102472. enableGroundShadow: true,
  102473. groundShadowLevel: 0.5,
  102474. enableGroundMirror: false,
  102475. groundMirrorSizeRatio: 0.3,
  102476. groundMirrorBlurKernel: 64,
  102477. groundMirrorAmount: 1,
  102478. groundMirrorFresnelWeight: 1,
  102479. groundMirrorFallOffDistance: 0,
  102480. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102481. groundYBias: 0.00001,
  102482. createSkybox: true,
  102483. skyboxSize: 20,
  102484. skyboxTexture: this._skyboxTextureCDNUrl,
  102485. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102486. backgroundYRotation: 0,
  102487. sizeAuto: true,
  102488. rootPosition: BABYLON.Vector3.Zero(),
  102489. setupImageProcessing: true,
  102490. environmentTexture: this._environmentTextureCDNUrl,
  102491. cameraExposure: 0.8,
  102492. cameraContrast: 1.2,
  102493. toneMappingEnabled: true,
  102494. };
  102495. };
  102496. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102497. /**
  102498. * Gets the root mesh created by the helper.
  102499. */
  102500. get: function () {
  102501. return this._rootMesh;
  102502. },
  102503. enumerable: true,
  102504. configurable: true
  102505. });
  102506. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102507. /**
  102508. * Gets the skybox created by the helper.
  102509. */
  102510. get: function () {
  102511. return this._skybox;
  102512. },
  102513. enumerable: true,
  102514. configurable: true
  102515. });
  102516. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102517. /**
  102518. * Gets the skybox texture created by the helper.
  102519. */
  102520. get: function () {
  102521. return this._skyboxTexture;
  102522. },
  102523. enumerable: true,
  102524. configurable: true
  102525. });
  102526. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102527. /**
  102528. * Gets the skybox material created by the helper.
  102529. */
  102530. get: function () {
  102531. return this._skyboxMaterial;
  102532. },
  102533. enumerable: true,
  102534. configurable: true
  102535. });
  102536. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102537. /**
  102538. * Gets the ground mesh created by the helper.
  102539. */
  102540. get: function () {
  102541. return this._ground;
  102542. },
  102543. enumerable: true,
  102544. configurable: true
  102545. });
  102546. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102547. /**
  102548. * Gets the ground texture created by the helper.
  102549. */
  102550. get: function () {
  102551. return this._groundTexture;
  102552. },
  102553. enumerable: true,
  102554. configurable: true
  102555. });
  102556. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102557. /**
  102558. * Gets the ground mirror created by the helper.
  102559. */
  102560. get: function () {
  102561. return this._groundMirror;
  102562. },
  102563. enumerable: true,
  102564. configurable: true
  102565. });
  102566. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102567. /**
  102568. * Gets the ground mirror render list to helps pushing the meshes
  102569. * you wish in the ground reflection.
  102570. */
  102571. get: function () {
  102572. if (this._groundMirror) {
  102573. return this._groundMirror.renderList;
  102574. }
  102575. return null;
  102576. },
  102577. enumerable: true,
  102578. configurable: true
  102579. });
  102580. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102581. /**
  102582. * Gets the ground material created by the helper.
  102583. */
  102584. get: function () {
  102585. return this._groundMaterial;
  102586. },
  102587. enumerable: true,
  102588. configurable: true
  102589. });
  102590. /**
  102591. * Updates the background according to the new options
  102592. * @param options
  102593. */
  102594. EnvironmentHelper.prototype.updateOptions = function (options) {
  102595. var newOptions = __assign({}, this._options, options);
  102596. if (this._ground && !newOptions.createGround) {
  102597. this._ground.dispose();
  102598. this._ground = null;
  102599. }
  102600. if (this._groundMaterial && !newOptions.createGround) {
  102601. this._groundMaterial.dispose();
  102602. this._groundMaterial = null;
  102603. }
  102604. if (this._groundTexture) {
  102605. if (this._options.groundTexture != newOptions.groundTexture) {
  102606. this._groundTexture.dispose();
  102607. this._groundTexture = null;
  102608. }
  102609. }
  102610. if (this._skybox && !newOptions.createSkybox) {
  102611. this._skybox.dispose();
  102612. this._skybox = null;
  102613. }
  102614. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102615. this._skyboxMaterial.dispose();
  102616. this._skyboxMaterial = null;
  102617. }
  102618. if (this._skyboxTexture) {
  102619. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102620. this._skyboxTexture.dispose();
  102621. this._skyboxTexture = null;
  102622. }
  102623. }
  102624. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102625. this._groundMirror.dispose();
  102626. this._groundMirror = null;
  102627. }
  102628. if (this._scene.environmentTexture) {
  102629. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102630. this._scene.environmentTexture.dispose();
  102631. }
  102632. }
  102633. this._options = newOptions;
  102634. this._setupBackground();
  102635. this._setupImageProcessing();
  102636. };
  102637. /**
  102638. * Sets the primary color of all the available elements.
  102639. * @param color the main color to affect to the ground and the background
  102640. */
  102641. EnvironmentHelper.prototype.setMainColor = function (color) {
  102642. if (this.groundMaterial) {
  102643. this.groundMaterial.primaryColor = color;
  102644. }
  102645. if (this.skyboxMaterial) {
  102646. this.skyboxMaterial.primaryColor = color;
  102647. }
  102648. if (this.groundMirror) {
  102649. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102650. }
  102651. };
  102652. /**
  102653. * Setup the image processing according to the specified options.
  102654. */
  102655. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102656. if (this._options.setupImageProcessing) {
  102657. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102658. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102659. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102660. this._setupEnvironmentTexture();
  102661. }
  102662. };
  102663. /**
  102664. * Setup the environment texture according to the specified options.
  102665. */
  102666. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102667. if (this._scene.environmentTexture) {
  102668. return;
  102669. }
  102670. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102671. this._scene.environmentTexture = this._options.environmentTexture;
  102672. return;
  102673. }
  102674. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102675. this._scene.environmentTexture = environmentTexture;
  102676. };
  102677. /**
  102678. * Setup the background according to the specified options.
  102679. */
  102680. EnvironmentHelper.prototype._setupBackground = function () {
  102681. if (!this._rootMesh) {
  102682. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102683. }
  102684. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102685. var sceneSize = this._getSceneSize();
  102686. if (this._options.createGround) {
  102687. this._setupGround(sceneSize);
  102688. this._setupGroundMaterial();
  102689. this._setupGroundDiffuseTexture();
  102690. if (this._options.enableGroundMirror) {
  102691. this._setupGroundMirrorTexture(sceneSize);
  102692. }
  102693. this._setupMirrorInGroundMaterial();
  102694. }
  102695. if (this._options.createSkybox) {
  102696. this._setupSkybox(sceneSize);
  102697. this._setupSkyboxMaterial();
  102698. this._setupSkyboxReflectionTexture();
  102699. }
  102700. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102701. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102702. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102703. };
  102704. /**
  102705. * Get the scene sizes according to the setup.
  102706. */
  102707. EnvironmentHelper.prototype._getSceneSize = function () {
  102708. var _this = this;
  102709. var groundSize = this._options.groundSize;
  102710. var skyboxSize = this._options.skyboxSize;
  102711. var rootPosition = this._options.rootPosition;
  102712. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102713. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102714. }
  102715. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102716. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102717. });
  102718. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102719. if (this._options.sizeAuto) {
  102720. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102721. this._scene.activeCamera.upperRadiusLimit) {
  102722. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102723. skyboxSize = groundSize;
  102724. }
  102725. var sceneDiagonalLenght = sceneDiagonal.length();
  102726. if (sceneDiagonalLenght > groundSize) {
  102727. groundSize = sceneDiagonalLenght * 2;
  102728. skyboxSize = groundSize;
  102729. }
  102730. // 10 % bigger.
  102731. groundSize *= 1.1;
  102732. skyboxSize *= 1.5;
  102733. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102734. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102735. }
  102736. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102737. };
  102738. /**
  102739. * Setup the ground according to the specified options.
  102740. */
  102741. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102742. var _this = this;
  102743. if (!this._ground || this._ground.isDisposed()) {
  102744. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102745. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102746. this._ground.parent = this._rootMesh;
  102747. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102748. }
  102749. this._ground.receiveShadows = this._options.enableGroundShadow;
  102750. };
  102751. /**
  102752. * Setup the ground material according to the specified options.
  102753. */
  102754. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102755. if (!this._groundMaterial) {
  102756. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102757. }
  102758. this._groundMaterial.alpha = this._options.groundOpacity;
  102759. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102760. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102761. this._groundMaterial.primaryColor = this._options.groundColor;
  102762. this._groundMaterial.useRGBColor = false;
  102763. this._groundMaterial.enableNoise = true;
  102764. if (this._ground) {
  102765. this._ground.material = this._groundMaterial;
  102766. }
  102767. };
  102768. /**
  102769. * Setup the ground diffuse texture according to the specified options.
  102770. */
  102771. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102772. if (!this._groundMaterial) {
  102773. return;
  102774. }
  102775. if (this._groundTexture) {
  102776. return;
  102777. }
  102778. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102779. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102780. return;
  102781. }
  102782. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102783. diffuseTexture.gammaSpace = false;
  102784. diffuseTexture.hasAlpha = true;
  102785. this._groundMaterial.diffuseTexture = diffuseTexture;
  102786. };
  102787. /**
  102788. * Setup the ground mirror texture according to the specified options.
  102789. */
  102790. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102791. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102792. if (!this._groundMirror) {
  102793. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102794. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102795. this._groundMirror.anisotropicFilteringLevel = 1;
  102796. this._groundMirror.wrapU = wrapping;
  102797. this._groundMirror.wrapV = wrapping;
  102798. this._groundMirror.gammaSpace = false;
  102799. if (this._groundMirror.renderList) {
  102800. for (var i = 0; i < this._scene.meshes.length; i++) {
  102801. var mesh = this._scene.meshes[i];
  102802. if (mesh !== this._ground &&
  102803. mesh !== this._skybox &&
  102804. mesh !== this._rootMesh) {
  102805. this._groundMirror.renderList.push(mesh);
  102806. }
  102807. }
  102808. }
  102809. }
  102810. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102811. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102812. };
  102813. /**
  102814. * Setup the ground to receive the mirror texture.
  102815. */
  102816. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102817. if (this._groundMaterial) {
  102818. this._groundMaterial.reflectionTexture = this._groundMirror;
  102819. this._groundMaterial.reflectionFresnel = true;
  102820. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102821. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102822. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102823. }
  102824. };
  102825. /**
  102826. * Setup the skybox according to the specified options.
  102827. */
  102828. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102829. var _this = this;
  102830. if (!this._skybox || this._skybox.isDisposed()) {
  102831. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102832. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102833. }
  102834. this._skybox.parent = this._rootMesh;
  102835. };
  102836. /**
  102837. * Setup the skybox material according to the specified options.
  102838. */
  102839. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102840. if (!this._skybox) {
  102841. return;
  102842. }
  102843. if (!this._skyboxMaterial) {
  102844. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102845. }
  102846. this._skyboxMaterial.useRGBColor = false;
  102847. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102848. this._skyboxMaterial.enableNoise = true;
  102849. this._skybox.material = this._skyboxMaterial;
  102850. };
  102851. /**
  102852. * Setup the skybox reflection texture according to the specified options.
  102853. */
  102854. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102855. if (!this._skyboxMaterial) {
  102856. return;
  102857. }
  102858. if (this._skyboxTexture) {
  102859. return;
  102860. }
  102861. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102862. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102863. return;
  102864. }
  102865. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102866. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102867. this._skyboxTexture.gammaSpace = false;
  102868. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102869. };
  102870. /**
  102871. * Dispose all the elements created by the Helper.
  102872. */
  102873. EnvironmentHelper.prototype.dispose = function () {
  102874. if (this._groundMaterial) {
  102875. this._groundMaterial.dispose(true, true);
  102876. }
  102877. if (this._skyboxMaterial) {
  102878. this._skyboxMaterial.dispose(true, true);
  102879. }
  102880. this._rootMesh.dispose(false);
  102881. };
  102882. /**
  102883. * Default ground texture URL.
  102884. */
  102885. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102886. /**
  102887. * Default skybox texture URL.
  102888. */
  102889. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102890. /**
  102891. * Default environment texture URL.
  102892. */
  102893. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102894. return EnvironmentHelper;
  102895. }());
  102896. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102897. })(BABYLON || (BABYLON = {}));
  102898. //# sourceMappingURL=babylon.environmentHelper.js.map
  102899. var BABYLON;
  102900. (function (BABYLON) {
  102901. /** Internal class used to store shapes for emitters */
  102902. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102903. function ParticleSystemSetEmitterCreationOptions() {
  102904. }
  102905. return ParticleSystemSetEmitterCreationOptions;
  102906. }());
  102907. /**
  102908. * Represents a set of particle systems working together to create a specific effect
  102909. */
  102910. var ParticleSystemSet = /** @class */ (function () {
  102911. function ParticleSystemSet() {
  102912. /**
  102913. * Gets the particle system list
  102914. */
  102915. this.systems = new Array();
  102916. }
  102917. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102918. /**
  102919. * Gets the emitter node used with this set
  102920. */
  102921. get: function () {
  102922. return this._emitterNode;
  102923. },
  102924. enumerable: true,
  102925. configurable: true
  102926. });
  102927. /**
  102928. * Creates a new emitter mesh as a sphere
  102929. * @param options defines the options used to create the sphere
  102930. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102931. * @param scene defines the hosting scene
  102932. */
  102933. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  102934. if (this._emitterNode) {
  102935. this._emitterNode.dispose();
  102936. }
  102937. this._emitterCreationOptions = {
  102938. kind: "Sphere",
  102939. options: options,
  102940. renderingGroupId: renderingGroupId
  102941. };
  102942. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  102943. emitterMesh.renderingGroupId = renderingGroupId;
  102944. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  102945. material.emissiveColor = options.color;
  102946. emitterMesh.material = material;
  102947. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102948. var system = _a[_i];
  102949. system.emitter = emitterMesh;
  102950. }
  102951. this._emitterNode = emitterMesh;
  102952. };
  102953. /**
  102954. * Starts all particle systems of the set
  102955. * @param emitter defines an optional mesh to use as emitter for the particle systems
  102956. */
  102957. ParticleSystemSet.prototype.start = function (emitter) {
  102958. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102959. var system = _a[_i];
  102960. if (emitter) {
  102961. system.emitter = emitter;
  102962. }
  102963. system.start();
  102964. }
  102965. };
  102966. /**
  102967. * Release all associated resources
  102968. */
  102969. ParticleSystemSet.prototype.dispose = function () {
  102970. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102971. var system = _a[_i];
  102972. system.dispose();
  102973. }
  102974. this.systems = [];
  102975. if (this._emitterNode) {
  102976. this._emitterNode.dispose();
  102977. this._emitterNode = null;
  102978. }
  102979. };
  102980. /**
  102981. * Serialize the set into a JSON compatible object
  102982. * @returns a JSON compatible representation of the set
  102983. */
  102984. ParticleSystemSet.prototype.serialize = function () {
  102985. var result = {};
  102986. result.systems = [];
  102987. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102988. var system = _a[_i];
  102989. result.systems.push(system.serialize());
  102990. }
  102991. if (this._emitterNode) {
  102992. result.emitter = this._emitterCreationOptions;
  102993. }
  102994. return result;
  102995. };
  102996. /**
  102997. * Parse a new ParticleSystemSet from a serialized source
  102998. * @param data defines a JSON compatible representation of the set
  102999. * @param scene defines the hosting scene
  103000. * @param gpu defines if we want GPU particles or CPU particles
  103001. * @returns a new ParticleSystemSet
  103002. */
  103003. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103004. if (gpu === void 0) { gpu = false; }
  103005. var result = new ParticleSystemSet();
  103006. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103007. scene = scene || BABYLON.Engine.LastCreatedScene;
  103008. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103009. var system = _a[_i];
  103010. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103011. }
  103012. if (data.emitter) {
  103013. var options = data.emitter.options;
  103014. switch (data.emitter.kind) {
  103015. case "Sphere":
  103016. result.setEmitterAsSphere({
  103017. diameter: options.diameter,
  103018. segments: options.segments,
  103019. color: BABYLON.Color3.FromArray(options.color)
  103020. }, data.emitter.renderingGroupId, scene);
  103021. break;
  103022. }
  103023. }
  103024. return result;
  103025. };
  103026. return ParticleSystemSet;
  103027. }());
  103028. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103029. })(BABYLON || (BABYLON = {}));
  103030. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103031. var BABYLON;
  103032. (function (BABYLON) {
  103033. /**
  103034. * This class is made for on one-liner static method to help creating particle system set.
  103035. */
  103036. var ParticleHelper = /** @class */ (function () {
  103037. function ParticleHelper() {
  103038. }
  103039. /**
  103040. * This is the main static method (one-liner) of this helper to create different particle systems
  103041. * @param type This string represents the type to the particle system to create
  103042. * @param scene The scene where the particle system should live
  103043. * @param gpu If the system will use gpu
  103044. * @returns the ParticleSystemSet created
  103045. */
  103046. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103047. if (gpu === void 0) { gpu = false; }
  103048. if (!scene) {
  103049. scene = BABYLON.Engine.LastCreatedScene;
  103050. ;
  103051. }
  103052. var token = {};
  103053. scene._addPendingData(token);
  103054. return new Promise(function (resolve, reject) {
  103055. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103056. scene._removePendingData(token);
  103057. return reject("Particle system with GPU is not supported.");
  103058. }
  103059. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103060. scene._removePendingData(token);
  103061. var newData = JSON.parse(data.toString());
  103062. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103063. }, undefined, undefined, undefined, function (req, exception) {
  103064. scene._removePendingData(token);
  103065. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103066. });
  103067. });
  103068. };
  103069. /**
  103070. * Static function used to export a particle system to a ParticleSystemSet variable.
  103071. * Please note that the emitter shape is not exported
  103072. * @param system defines the particle systems to export
  103073. */
  103074. ParticleHelper.ExportSet = function (systems) {
  103075. var set = new BABYLON.ParticleSystemSet();
  103076. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103077. var system = systems_1[_i];
  103078. set.systems.push(system);
  103079. }
  103080. return set;
  103081. };
  103082. /**
  103083. * Gets or sets base Assets URL
  103084. */
  103085. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103086. return ParticleHelper;
  103087. }());
  103088. BABYLON.ParticleHelper = ParticleHelper;
  103089. })(BABYLON || (BABYLON = {}));
  103090. //# sourceMappingURL=babylon.particleHelper.js.map
  103091. var BABYLON;
  103092. (function (BABYLON) {
  103093. /**
  103094. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103095. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103096. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103097. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103098. */
  103099. var VideoDome = /** @class */ (function (_super) {
  103100. __extends(VideoDome, _super);
  103101. /**
  103102. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103103. * @param name Element's name, child elements will append suffixes for their own names.
  103104. * @param urlsOrVideo defines the url(s) or the video element to use
  103105. * @param options An object containing optional or exposed sub element properties
  103106. */
  103107. function VideoDome(name, urlsOrVideo, options, scene) {
  103108. var _this = _super.call(this, name, scene) || this;
  103109. _this._useDirectMapping = false;
  103110. // set defaults and manage values
  103111. name = name || "videoDome";
  103112. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103113. options.clickToPlay = Boolean(options.clickToPlay);
  103114. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103115. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103116. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103117. if (options.useDirectMapping === undefined) {
  103118. _this._useDirectMapping = true;
  103119. }
  103120. else {
  103121. _this._useDirectMapping = options.useDirectMapping;
  103122. }
  103123. // create
  103124. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103125. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103126. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103127. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103128. // configure material
  103129. material.useEquirectangularFOV = true;
  103130. material.fovMultiplier = 1.0;
  103131. material.opacityFresnel = false;
  103132. if (_this._useDirectMapping) {
  103133. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103134. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103135. material.diffuseTexture = texture;
  103136. }
  103137. else {
  103138. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103139. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103140. material.reflectionTexture = texture;
  103141. }
  103142. // configure mesh
  103143. _this._mesh.material = material;
  103144. _this._mesh.parent = _this;
  103145. // optional configuration
  103146. if (options.clickToPlay) {
  103147. scene.onPointerUp = function () {
  103148. _this._videoTexture.video.play();
  103149. };
  103150. }
  103151. return _this;
  103152. }
  103153. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103154. /**
  103155. * Gets the video texture being displayed on the sphere
  103156. */
  103157. get: function () {
  103158. return this._videoTexture;
  103159. },
  103160. enumerable: true,
  103161. configurable: true
  103162. });
  103163. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103164. /**
  103165. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103166. * Also see the options.resolution property.
  103167. */
  103168. get: function () {
  103169. return this._material.fovMultiplier;
  103170. },
  103171. set: function (value) {
  103172. this._material.fovMultiplier = value;
  103173. },
  103174. enumerable: true,
  103175. configurable: true
  103176. });
  103177. /**
  103178. * Releases resources associated with this node.
  103179. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103180. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103181. */
  103182. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103183. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103184. this._videoTexture.dispose();
  103185. this._mesh.dispose();
  103186. this._material.dispose();
  103187. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103188. };
  103189. return VideoDome;
  103190. }(BABYLON.Node));
  103191. BABYLON.VideoDome = VideoDome;
  103192. })(BABYLON || (BABYLON = {}));
  103193. //# sourceMappingURL=babylon.videoDome.js.map
  103194. var BABYLON;
  103195. (function (BABYLON) {
  103196. /**
  103197. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103198. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103199. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103200. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103201. */
  103202. var PhotoDome = /** @class */ (function (_super) {
  103203. __extends(PhotoDome, _super);
  103204. /**
  103205. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103206. * @param name Element's name, child elements will append suffixes for their own names.
  103207. * @param urlsOfPhoto define the url of the photo to display
  103208. * @param options An object containing optional or exposed sub element properties
  103209. */
  103210. function PhotoDome(name, urlOfPhoto, options, scene) {
  103211. var _this = _super.call(this, name, scene) || this;
  103212. _this._useDirectMapping = false;
  103213. // set defaults and manage values
  103214. name = name || "photoDome";
  103215. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103216. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103217. if (options.useDirectMapping === undefined) {
  103218. _this._useDirectMapping = true;
  103219. }
  103220. else {
  103221. _this._useDirectMapping = options.useDirectMapping;
  103222. }
  103223. // create
  103224. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103225. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103226. // configure material
  103227. material.opacityFresnel = false;
  103228. material.useEquirectangularFOV = true;
  103229. material.fovMultiplier = 1.0;
  103230. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103231. // configure mesh
  103232. _this._mesh.material = material;
  103233. _this._mesh.parent = _this;
  103234. return _this;
  103235. }
  103236. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103237. /**
  103238. * Gets or sets the texture being displayed on the sphere
  103239. */
  103240. get: function () {
  103241. return this._photoTexture;
  103242. },
  103243. set: function (value) {
  103244. if (this._photoTexture === value) {
  103245. return;
  103246. }
  103247. this._photoTexture = value;
  103248. if (this._useDirectMapping) {
  103249. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103250. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103251. this._material.diffuseTexture = this._photoTexture;
  103252. }
  103253. else {
  103254. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103255. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103256. this._material.reflectionTexture = this._photoTexture;
  103257. }
  103258. },
  103259. enumerable: true,
  103260. configurable: true
  103261. });
  103262. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103263. /**
  103264. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103265. * Also see the options.resolution property.
  103266. */
  103267. get: function () {
  103268. return this._material.fovMultiplier;
  103269. },
  103270. set: function (value) {
  103271. this._material.fovMultiplier = value;
  103272. },
  103273. enumerable: true,
  103274. configurable: true
  103275. });
  103276. /**
  103277. * Releases resources associated with this node.
  103278. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103279. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103280. */
  103281. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103282. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103283. this._photoTexture.dispose();
  103284. this._mesh.dispose();
  103285. this._material.dispose();
  103286. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103287. };
  103288. return PhotoDome;
  103289. }(BABYLON.Node));
  103290. BABYLON.PhotoDome = PhotoDome;
  103291. })(BABYLON || (BABYLON = {}));
  103292. //# sourceMappingURL=babylon.photoDome.js.map
  103293. 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;\nuniform vec2 translationPivot;\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\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\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;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \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=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\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#endif\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 worldPos=rotate(yaxis,rotatedCorner);\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 mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\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\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\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;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \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=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\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 mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 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 vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.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(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction;\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\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"};
  103294. 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=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  103295. globalObject["BABYLON"] = BABYLON;
  103296. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var serializeAsCameraReference = BABYLON.serializeAsCameraReference;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var ColorGradient = BABYLON.ColorGradient;var FactorGradient = BABYLON.FactorGradient;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var SceneComponentConstants = BABYLON.SceneComponentConstants;var Stage = BABYLON.Stage;var AbstractScene = BABYLON.AbstractScene;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RawCubeTexture = BABYLON.RawCubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcessManager = BABYLON.PostProcessManager;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var EnvironmentTextureTools = BABYLON.EnvironmentTextureTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystemSceneComponent = BABYLON.LensFlareSystemSceneComponent;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var PointerDragBehavior = BABYLON.PointerDragBehavior;var MultiPointerScaleBehavior = BABYLON.MultiPointerScaleBehavior;var SixDofDragBehavior = BABYLON.SixDofDragBehavior;var Gizmo = BABYLON.Gizmo;var AxisDragGizmo = BABYLON.AxisDragGizmo;var AxisScaleGizmo = BABYLON.AxisScaleGizmo;var PlaneRotationGizmo = BABYLON.PlaneRotationGizmo;var PositionGizmo = BABYLON.PositionGizmo;var RotationGizmo = BABYLON.RotationGizmo;var ScaleGizmo = BABYLON.ScaleGizmo;var BoundingBoxGizmo = BABYLON.BoundingBoxGizmo;var GizmoManager = BABYLON.GizmoManager;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayerSceneComponent = BABYLON.EffectLayerSceneComponent;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var LayerSceneComponent = BABYLON.LayerSceneComponent;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var ParticleSystemSet = BABYLON.ParticleSystemSet;var ParticleHelper = BABYLON.ParticleHelper;var VideoDome = BABYLON.VideoDome;var PhotoDome = BABYLON.PhotoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var Debug = BABYLON.Debug ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  103297. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,ColorGradient,FactorGradient,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,SceneComponentConstants,Stage,AbstractScene,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PerformanceMonitor,RollingAverage,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RawCubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcessManager,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,EnvironmentTextureTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystemSceneComponent,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,RayHelper,DebugLayer,BoundingBoxRenderer,UtilityLayerRenderer,PointerDragBehavior,MultiPointerScaleBehavior,SixDofDragBehavior,Gizmo,AxisDragGizmo,AxisScaleGizmo,PlaneRotationGizmo,PositionGizmo,RotationGizmo,ScaleGizmo,BoundingBoxGizmo,GizmoManager,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayerSceneComponent,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,LayerSceneComponent,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleSystemSet,ParticleHelper,VideoDome,PhotoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };